mmu.c 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015
  1. /*
  2. * Kernel-based Virtual Machine driver for Linux
  3. *
  4. * This module enables machines with Intel VT-x extensions to run virtual
  5. * machines without emulation or binary translation.
  6. *
  7. * MMU support
  8. *
  9. * Copyright (C) 2006 Qumranet, Inc.
  10. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  11. *
  12. * Authors:
  13. * Yaniv Kamay <yaniv@qumranet.com>
  14. * Avi Kivity <avi@qumranet.com>
  15. *
  16. * This work is licensed under the terms of the GNU GPL, version 2. See
  17. * the COPYING file in the top-level directory.
  18. *
  19. */
  20. #include "irq.h"
  21. #include "mmu.h"
  22. #include "x86.h"
  23. #include "kvm_cache_regs.h"
  24. #include "cpuid.h"
  25. #include <linux/kvm_host.h>
  26. #include <linux/types.h>
  27. #include <linux/string.h>
  28. #include <linux/mm.h>
  29. #include <linux/highmem.h>
  30. #include <linux/moduleparam.h>
  31. #include <linux/export.h>
  32. #include <linux/swap.h>
  33. #include <linux/hugetlb.h>
  34. #include <linux/compiler.h>
  35. #include <linux/srcu.h>
  36. #include <linux/slab.h>
  37. #include <linux/sched/signal.h>
  38. #include <linux/uaccess.h>
  39. #include <linux/hash.h>
  40. #include <linux/kern_levels.h>
  41. #include <asm/page.h>
  42. #include <asm/pat.h>
  43. #include <asm/cmpxchg.h>
  44. #include <asm/io.h>
  45. #include <asm/vmx.h>
  46. #include <asm/kvm_page_track.h>
  47. #include "trace.h"
  48. /*
  49. * When setting this variable to true it enables Two-Dimensional-Paging
  50. * where the hardware walks 2 page tables:
  51. * 1. the guest-virtual to guest-physical
  52. * 2. while doing 1. it walks guest-physical to host-physical
  53. * If the hardware supports that we don't need to do shadow paging.
  54. */
  55. bool tdp_enabled = false;
  56. enum {
  57. AUDIT_PRE_PAGE_FAULT,
  58. AUDIT_POST_PAGE_FAULT,
  59. AUDIT_PRE_PTE_WRITE,
  60. AUDIT_POST_PTE_WRITE,
  61. AUDIT_PRE_SYNC,
  62. AUDIT_POST_SYNC
  63. };
  64. #undef MMU_DEBUG
  65. #ifdef MMU_DEBUG
  66. static bool dbg = 0;
  67. module_param(dbg, bool, 0644);
  68. #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
  69. #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
  70. #define MMU_WARN_ON(x) WARN_ON(x)
  71. #else
  72. #define pgprintk(x...) do { } while (0)
  73. #define rmap_printk(x...) do { } while (0)
  74. #define MMU_WARN_ON(x) do { } while (0)
  75. #endif
  76. #define PTE_PREFETCH_NUM 8
  77. #define PT_FIRST_AVAIL_BITS_SHIFT 10
  78. #define PT64_SECOND_AVAIL_BITS_SHIFT 52
  79. #define PT64_LEVEL_BITS 9
  80. #define PT64_LEVEL_SHIFT(level) \
  81. (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
  82. #define PT64_INDEX(address, level)\
  83. (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
  84. #define PT32_LEVEL_BITS 10
  85. #define PT32_LEVEL_SHIFT(level) \
  86. (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
  87. #define PT32_LVL_OFFSET_MASK(level) \
  88. (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
  89. * PT32_LEVEL_BITS))) - 1))
  90. #define PT32_INDEX(address, level)\
  91. (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
  92. #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
  93. #define PT64_DIR_BASE_ADDR_MASK \
  94. (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
  95. #define PT64_LVL_ADDR_MASK(level) \
  96. (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
  97. * PT64_LEVEL_BITS))) - 1))
  98. #define PT64_LVL_OFFSET_MASK(level) \
  99. (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
  100. * PT64_LEVEL_BITS))) - 1))
  101. #define PT32_BASE_ADDR_MASK PAGE_MASK
  102. #define PT32_DIR_BASE_ADDR_MASK \
  103. (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
  104. #define PT32_LVL_ADDR_MASK(level) \
  105. (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
  106. * PT32_LEVEL_BITS))) - 1))
  107. #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
  108. | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
  109. #define ACC_EXEC_MASK 1
  110. #define ACC_WRITE_MASK PT_WRITABLE_MASK
  111. #define ACC_USER_MASK PT_USER_MASK
  112. #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
  113. /* The mask for the R/X bits in EPT PTEs */
  114. #define PT64_EPT_READABLE_MASK 0x1ull
  115. #define PT64_EPT_EXECUTABLE_MASK 0x4ull
  116. #include <trace/events/kvm.h>
  117. #define CREATE_TRACE_POINTS
  118. #include "mmutrace.h"
  119. #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
  120. #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
  121. #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
  122. /* make pte_list_desc fit well in cache line */
  123. #define PTE_LIST_EXT 3
  124. /*
  125. * Return values of handle_mmio_page_fault and mmu.page_fault:
  126. * RET_PF_RETRY: let CPU fault again on the address.
  127. * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
  128. *
  129. * For handle_mmio_page_fault only:
  130. * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
  131. */
  132. enum {
  133. RET_PF_RETRY = 0,
  134. RET_PF_EMULATE = 1,
  135. RET_PF_INVALID = 2,
  136. };
  137. struct pte_list_desc {
  138. u64 *sptes[PTE_LIST_EXT];
  139. struct pte_list_desc *more;
  140. };
  141. struct kvm_shadow_walk_iterator {
  142. u64 addr;
  143. hpa_t shadow_addr;
  144. u64 *sptep;
  145. int level;
  146. unsigned index;
  147. };
  148. static const union kvm_mmu_page_role mmu_base_role_mask = {
  149. .cr0_wp = 1,
  150. .cr4_pae = 1,
  151. .nxe = 1,
  152. .smep_andnot_wp = 1,
  153. .smap_andnot_wp = 1,
  154. .smm = 1,
  155. .guest_mode = 1,
  156. .ad_disabled = 1,
  157. };
  158. #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
  159. for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
  160. (_root), (_addr)); \
  161. shadow_walk_okay(&(_walker)); \
  162. shadow_walk_next(&(_walker)))
  163. #define for_each_shadow_entry(_vcpu, _addr, _walker) \
  164. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  165. shadow_walk_okay(&(_walker)); \
  166. shadow_walk_next(&(_walker)))
  167. #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
  168. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  169. shadow_walk_okay(&(_walker)) && \
  170. ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
  171. __shadow_walk_next(&(_walker), spte))
  172. static struct kmem_cache *pte_list_desc_cache;
  173. static struct kmem_cache *mmu_page_header_cache;
  174. static struct percpu_counter kvm_total_used_mmu_pages;
  175. static u64 __read_mostly shadow_nx_mask;
  176. static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
  177. static u64 __read_mostly shadow_user_mask;
  178. static u64 __read_mostly shadow_accessed_mask;
  179. static u64 __read_mostly shadow_dirty_mask;
  180. static u64 __read_mostly shadow_mmio_mask;
  181. static u64 __read_mostly shadow_mmio_value;
  182. static u64 __read_mostly shadow_present_mask;
  183. static u64 __read_mostly shadow_me_mask;
  184. /*
  185. * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
  186. * Non-present SPTEs with shadow_acc_track_value set are in place for access
  187. * tracking.
  188. */
  189. static u64 __read_mostly shadow_acc_track_mask;
  190. static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
  191. /*
  192. * The mask/shift to use for saving the original R/X bits when marking the PTE
  193. * as not-present for access tracking purposes. We do not save the W bit as the
  194. * PTEs being access tracked also need to be dirty tracked, so the W bit will be
  195. * restored only when a write is attempted to the page.
  196. */
  197. static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
  198. PT64_EPT_EXECUTABLE_MASK;
  199. static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
  200. /*
  201. * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
  202. * to guard against L1TF attacks.
  203. */
  204. static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  205. /*
  206. * The number of high-order 1 bits to use in the mask above.
  207. */
  208. static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
  209. /*
  210. * In some cases, we need to preserve the GFN of a non-present or reserved
  211. * SPTE when we usurp the upper five bits of the physical address space to
  212. * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
  213. * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
  214. * left into the reserved bits, i.e. the GFN in the SPTE will be split into
  215. * high and low parts. This mask covers the lower bits of the GFN.
  216. */
  217. static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
  218. static void mmu_spte_set(u64 *sptep, u64 spte);
  219. static union kvm_mmu_page_role
  220. kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
  221. void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
  222. {
  223. BUG_ON((mmio_mask & mmio_value) != mmio_value);
  224. shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
  225. shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
  226. }
  227. EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
  228. static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
  229. {
  230. return sp->role.ad_disabled;
  231. }
  232. static inline bool spte_ad_enabled(u64 spte)
  233. {
  234. MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
  235. return !(spte & shadow_acc_track_value);
  236. }
  237. static inline u64 spte_shadow_accessed_mask(u64 spte)
  238. {
  239. MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
  240. return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
  241. }
  242. static inline u64 spte_shadow_dirty_mask(u64 spte)
  243. {
  244. MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
  245. return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
  246. }
  247. static inline bool is_access_track_spte(u64 spte)
  248. {
  249. return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
  250. }
  251. /*
  252. * the low bit of the generation number is always presumed to be zero.
  253. * This disables mmio caching during memslot updates. The concept is
  254. * similar to a seqcount but instead of retrying the access we just punt
  255. * and ignore the cache.
  256. *
  257. * spte bits 3-11 are used as bits 1-9 of the generation number,
  258. * the bits 52-61 are used as bits 10-19 of the generation number.
  259. */
  260. #define MMIO_SPTE_GEN_LOW_SHIFT 2
  261. #define MMIO_SPTE_GEN_HIGH_SHIFT 52
  262. #define MMIO_GEN_SHIFT 20
  263. #define MMIO_GEN_LOW_SHIFT 10
  264. #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
  265. #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
  266. static u64 generation_mmio_spte_mask(unsigned int gen)
  267. {
  268. u64 mask;
  269. WARN_ON(gen & ~MMIO_GEN_MASK);
  270. mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
  271. mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
  272. return mask;
  273. }
  274. static unsigned int get_mmio_spte_generation(u64 spte)
  275. {
  276. unsigned int gen;
  277. spte &= ~shadow_mmio_mask;
  278. gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
  279. gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
  280. return gen;
  281. }
  282. static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
  283. {
  284. return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
  285. }
  286. static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
  287. unsigned access)
  288. {
  289. unsigned int gen = kvm_current_mmio_generation(vcpu);
  290. u64 mask = generation_mmio_spte_mask(gen);
  291. u64 gpa = gfn << PAGE_SHIFT;
  292. access &= ACC_WRITE_MASK | ACC_USER_MASK;
  293. mask |= shadow_mmio_value | access;
  294. mask |= gpa | shadow_nonpresent_or_rsvd_mask;
  295. mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
  296. << shadow_nonpresent_or_rsvd_mask_len;
  297. trace_mark_mmio_spte(sptep, gfn, access, gen);
  298. mmu_spte_set(sptep, mask);
  299. }
  300. static bool is_mmio_spte(u64 spte)
  301. {
  302. return (spte & shadow_mmio_mask) == shadow_mmio_value;
  303. }
  304. static gfn_t get_mmio_spte_gfn(u64 spte)
  305. {
  306. u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
  307. gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
  308. & shadow_nonpresent_or_rsvd_mask;
  309. return gpa >> PAGE_SHIFT;
  310. }
  311. static unsigned get_mmio_spte_access(u64 spte)
  312. {
  313. u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
  314. return (spte & ~mask) & ~PAGE_MASK;
  315. }
  316. static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
  317. kvm_pfn_t pfn, unsigned access)
  318. {
  319. if (unlikely(is_noslot_pfn(pfn))) {
  320. mark_mmio_spte(vcpu, sptep, gfn, access);
  321. return true;
  322. }
  323. return false;
  324. }
  325. static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
  326. {
  327. unsigned int kvm_gen, spte_gen;
  328. kvm_gen = kvm_current_mmio_generation(vcpu);
  329. spte_gen = get_mmio_spte_generation(spte);
  330. trace_check_mmio_spte(spte, kvm_gen, spte_gen);
  331. return likely(kvm_gen == spte_gen);
  332. }
  333. /*
  334. * Sets the shadow PTE masks used by the MMU.
  335. *
  336. * Assumptions:
  337. * - Setting either @accessed_mask or @dirty_mask requires setting both
  338. * - At least one of @accessed_mask or @acc_track_mask must be set
  339. */
  340. void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
  341. u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
  342. u64 acc_track_mask, u64 me_mask)
  343. {
  344. BUG_ON(!dirty_mask != !accessed_mask);
  345. BUG_ON(!accessed_mask && !acc_track_mask);
  346. BUG_ON(acc_track_mask & shadow_acc_track_value);
  347. shadow_user_mask = user_mask;
  348. shadow_accessed_mask = accessed_mask;
  349. shadow_dirty_mask = dirty_mask;
  350. shadow_nx_mask = nx_mask;
  351. shadow_x_mask = x_mask;
  352. shadow_present_mask = p_mask;
  353. shadow_acc_track_mask = acc_track_mask;
  354. shadow_me_mask = me_mask;
  355. }
  356. EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
  357. static void kvm_mmu_reset_all_pte_masks(void)
  358. {
  359. u8 low_phys_bits;
  360. shadow_user_mask = 0;
  361. shadow_accessed_mask = 0;
  362. shadow_dirty_mask = 0;
  363. shadow_nx_mask = 0;
  364. shadow_x_mask = 0;
  365. shadow_mmio_mask = 0;
  366. shadow_present_mask = 0;
  367. shadow_acc_track_mask = 0;
  368. /*
  369. * If the CPU has 46 or less physical address bits, then set an
  370. * appropriate mask to guard against L1TF attacks. Otherwise, it is
  371. * assumed that the CPU is not vulnerable to L1TF.
  372. */
  373. low_phys_bits = boot_cpu_data.x86_phys_bits;
  374. if (boot_cpu_data.x86_phys_bits <
  375. 52 - shadow_nonpresent_or_rsvd_mask_len) {
  376. shadow_nonpresent_or_rsvd_mask =
  377. rsvd_bits(boot_cpu_data.x86_phys_bits -
  378. shadow_nonpresent_or_rsvd_mask_len,
  379. boot_cpu_data.x86_phys_bits - 1);
  380. low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
  381. }
  382. shadow_nonpresent_or_rsvd_lower_gfn_mask =
  383. GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
  384. }
  385. static int is_cpuid_PSE36(void)
  386. {
  387. return 1;
  388. }
  389. static int is_nx(struct kvm_vcpu *vcpu)
  390. {
  391. return vcpu->arch.efer & EFER_NX;
  392. }
  393. static int is_shadow_present_pte(u64 pte)
  394. {
  395. return (pte != 0) && !is_mmio_spte(pte);
  396. }
  397. static int is_large_pte(u64 pte)
  398. {
  399. return pte & PT_PAGE_SIZE_MASK;
  400. }
  401. static int is_last_spte(u64 pte, int level)
  402. {
  403. if (level == PT_PAGE_TABLE_LEVEL)
  404. return 1;
  405. if (is_large_pte(pte))
  406. return 1;
  407. return 0;
  408. }
  409. static bool is_executable_pte(u64 spte)
  410. {
  411. return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
  412. }
  413. static kvm_pfn_t spte_to_pfn(u64 pte)
  414. {
  415. return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
  416. }
  417. static gfn_t pse36_gfn_delta(u32 gpte)
  418. {
  419. int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
  420. return (gpte & PT32_DIR_PSE36_MASK) << shift;
  421. }
  422. #ifdef CONFIG_X86_64
  423. static void __set_spte(u64 *sptep, u64 spte)
  424. {
  425. WRITE_ONCE(*sptep, spte);
  426. }
  427. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  428. {
  429. WRITE_ONCE(*sptep, spte);
  430. }
  431. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  432. {
  433. return xchg(sptep, spte);
  434. }
  435. static u64 __get_spte_lockless(u64 *sptep)
  436. {
  437. return READ_ONCE(*sptep);
  438. }
  439. #else
  440. union split_spte {
  441. struct {
  442. u32 spte_low;
  443. u32 spte_high;
  444. };
  445. u64 spte;
  446. };
  447. static void count_spte_clear(u64 *sptep, u64 spte)
  448. {
  449. struct kvm_mmu_page *sp = page_header(__pa(sptep));
  450. if (is_shadow_present_pte(spte))
  451. return;
  452. /* Ensure the spte is completely set before we increase the count */
  453. smp_wmb();
  454. sp->clear_spte_count++;
  455. }
  456. static void __set_spte(u64 *sptep, u64 spte)
  457. {
  458. union split_spte *ssptep, sspte;
  459. ssptep = (union split_spte *)sptep;
  460. sspte = (union split_spte)spte;
  461. ssptep->spte_high = sspte.spte_high;
  462. /*
  463. * If we map the spte from nonpresent to present, We should store
  464. * the high bits firstly, then set present bit, so cpu can not
  465. * fetch this spte while we are setting the spte.
  466. */
  467. smp_wmb();
  468. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  469. }
  470. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  471. {
  472. union split_spte *ssptep, sspte;
  473. ssptep = (union split_spte *)sptep;
  474. sspte = (union split_spte)spte;
  475. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  476. /*
  477. * If we map the spte from present to nonpresent, we should clear
  478. * present bit firstly to avoid vcpu fetch the old high bits.
  479. */
  480. smp_wmb();
  481. ssptep->spte_high = sspte.spte_high;
  482. count_spte_clear(sptep, spte);
  483. }
  484. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  485. {
  486. union split_spte *ssptep, sspte, orig;
  487. ssptep = (union split_spte *)sptep;
  488. sspte = (union split_spte)spte;
  489. /* xchg acts as a barrier before the setting of the high bits */
  490. orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
  491. orig.spte_high = ssptep->spte_high;
  492. ssptep->spte_high = sspte.spte_high;
  493. count_spte_clear(sptep, spte);
  494. return orig.spte;
  495. }
  496. /*
  497. * The idea using the light way get the spte on x86_32 guest is from
  498. * gup_get_pte(arch/x86/mm/gup.c).
  499. *
  500. * An spte tlb flush may be pending, because kvm_set_pte_rmapp
  501. * coalesces them and we are running out of the MMU lock. Therefore
  502. * we need to protect against in-progress updates of the spte.
  503. *
  504. * Reading the spte while an update is in progress may get the old value
  505. * for the high part of the spte. The race is fine for a present->non-present
  506. * change (because the high part of the spte is ignored for non-present spte),
  507. * but for a present->present change we must reread the spte.
  508. *
  509. * All such changes are done in two steps (present->non-present and
  510. * non-present->present), hence it is enough to count the number of
  511. * present->non-present updates: if it changed while reading the spte,
  512. * we might have hit the race. This is done using clear_spte_count.
  513. */
  514. static u64 __get_spte_lockless(u64 *sptep)
  515. {
  516. struct kvm_mmu_page *sp = page_header(__pa(sptep));
  517. union split_spte spte, *orig = (union split_spte *)sptep;
  518. int count;
  519. retry:
  520. count = sp->clear_spte_count;
  521. smp_rmb();
  522. spte.spte_low = orig->spte_low;
  523. smp_rmb();
  524. spte.spte_high = orig->spte_high;
  525. smp_rmb();
  526. if (unlikely(spte.spte_low != orig->spte_low ||
  527. count != sp->clear_spte_count))
  528. goto retry;
  529. return spte.spte;
  530. }
  531. #endif
  532. static bool spte_can_locklessly_be_made_writable(u64 spte)
  533. {
  534. return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
  535. (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
  536. }
  537. static bool spte_has_volatile_bits(u64 spte)
  538. {
  539. if (!is_shadow_present_pte(spte))
  540. return false;
  541. /*
  542. * Always atomically update spte if it can be updated
  543. * out of mmu-lock, it can ensure dirty bit is not lost,
  544. * also, it can help us to get a stable is_writable_pte()
  545. * to ensure tlb flush is not missed.
  546. */
  547. if (spte_can_locklessly_be_made_writable(spte) ||
  548. is_access_track_spte(spte))
  549. return true;
  550. if (spte_ad_enabled(spte)) {
  551. if ((spte & shadow_accessed_mask) == 0 ||
  552. (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
  553. return true;
  554. }
  555. return false;
  556. }
  557. static bool is_accessed_spte(u64 spte)
  558. {
  559. u64 accessed_mask = spte_shadow_accessed_mask(spte);
  560. return accessed_mask ? spte & accessed_mask
  561. : !is_access_track_spte(spte);
  562. }
  563. static bool is_dirty_spte(u64 spte)
  564. {
  565. u64 dirty_mask = spte_shadow_dirty_mask(spte);
  566. return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
  567. }
  568. /* Rules for using mmu_spte_set:
  569. * Set the sptep from nonpresent to present.
  570. * Note: the sptep being assigned *must* be either not present
  571. * or in a state where the hardware will not attempt to update
  572. * the spte.
  573. */
  574. static void mmu_spte_set(u64 *sptep, u64 new_spte)
  575. {
  576. WARN_ON(is_shadow_present_pte(*sptep));
  577. __set_spte(sptep, new_spte);
  578. }
  579. /*
  580. * Update the SPTE (excluding the PFN), but do not track changes in its
  581. * accessed/dirty status.
  582. */
  583. static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
  584. {
  585. u64 old_spte = *sptep;
  586. WARN_ON(!is_shadow_present_pte(new_spte));
  587. if (!is_shadow_present_pte(old_spte)) {
  588. mmu_spte_set(sptep, new_spte);
  589. return old_spte;
  590. }
  591. if (!spte_has_volatile_bits(old_spte))
  592. __update_clear_spte_fast(sptep, new_spte);
  593. else
  594. old_spte = __update_clear_spte_slow(sptep, new_spte);
  595. WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
  596. return old_spte;
  597. }
  598. /* Rules for using mmu_spte_update:
  599. * Update the state bits, it means the mapped pfn is not changed.
  600. *
  601. * Whenever we overwrite a writable spte with a read-only one we
  602. * should flush remote TLBs. Otherwise rmap_write_protect
  603. * will find a read-only spte, even though the writable spte
  604. * might be cached on a CPU's TLB, the return value indicates this
  605. * case.
  606. *
  607. * Returns true if the TLB needs to be flushed
  608. */
  609. static bool mmu_spte_update(u64 *sptep, u64 new_spte)
  610. {
  611. bool flush = false;
  612. u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
  613. if (!is_shadow_present_pte(old_spte))
  614. return false;
  615. /*
  616. * For the spte updated out of mmu-lock is safe, since
  617. * we always atomically update it, see the comments in
  618. * spte_has_volatile_bits().
  619. */
  620. if (spte_can_locklessly_be_made_writable(old_spte) &&
  621. !is_writable_pte(new_spte))
  622. flush = true;
  623. /*
  624. * Flush TLB when accessed/dirty states are changed in the page tables,
  625. * to guarantee consistency between TLB and page tables.
  626. */
  627. if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
  628. flush = true;
  629. kvm_set_pfn_accessed(spte_to_pfn(old_spte));
  630. }
  631. if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
  632. flush = true;
  633. kvm_set_pfn_dirty(spte_to_pfn(old_spte));
  634. }
  635. return flush;
  636. }
  637. /*
  638. * Rules for using mmu_spte_clear_track_bits:
  639. * It sets the sptep from present to nonpresent, and track the
  640. * state bits, it is used to clear the last level sptep.
  641. * Returns non-zero if the PTE was previously valid.
  642. */
  643. static int mmu_spte_clear_track_bits(u64 *sptep)
  644. {
  645. kvm_pfn_t pfn;
  646. u64 old_spte = *sptep;
  647. if (!spte_has_volatile_bits(old_spte))
  648. __update_clear_spte_fast(sptep, 0ull);
  649. else
  650. old_spte = __update_clear_spte_slow(sptep, 0ull);
  651. if (!is_shadow_present_pte(old_spte))
  652. return 0;
  653. pfn = spte_to_pfn(old_spte);
  654. /*
  655. * KVM does not hold the refcount of the page used by
  656. * kvm mmu, before reclaiming the page, we should
  657. * unmap it from mmu first.
  658. */
  659. WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
  660. if (is_accessed_spte(old_spte))
  661. kvm_set_pfn_accessed(pfn);
  662. if (is_dirty_spte(old_spte))
  663. kvm_set_pfn_dirty(pfn);
  664. return 1;
  665. }
  666. /*
  667. * Rules for using mmu_spte_clear_no_track:
  668. * Directly clear spte without caring the state bits of sptep,
  669. * it is used to set the upper level spte.
  670. */
  671. static void mmu_spte_clear_no_track(u64 *sptep)
  672. {
  673. __update_clear_spte_fast(sptep, 0ull);
  674. }
  675. static u64 mmu_spte_get_lockless(u64 *sptep)
  676. {
  677. return __get_spte_lockless(sptep);
  678. }
  679. static u64 mark_spte_for_access_track(u64 spte)
  680. {
  681. if (spte_ad_enabled(spte))
  682. return spte & ~shadow_accessed_mask;
  683. if (is_access_track_spte(spte))
  684. return spte;
  685. /*
  686. * Making an Access Tracking PTE will result in removal of write access
  687. * from the PTE. So, verify that we will be able to restore the write
  688. * access in the fast page fault path later on.
  689. */
  690. WARN_ONCE((spte & PT_WRITABLE_MASK) &&
  691. !spte_can_locklessly_be_made_writable(spte),
  692. "kvm: Writable SPTE is not locklessly dirty-trackable\n");
  693. WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
  694. shadow_acc_track_saved_bits_shift),
  695. "kvm: Access Tracking saved bit locations are not zero\n");
  696. spte |= (spte & shadow_acc_track_saved_bits_mask) <<
  697. shadow_acc_track_saved_bits_shift;
  698. spte &= ~shadow_acc_track_mask;
  699. return spte;
  700. }
  701. /* Restore an acc-track PTE back to a regular PTE */
  702. static u64 restore_acc_track_spte(u64 spte)
  703. {
  704. u64 new_spte = spte;
  705. u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
  706. & shadow_acc_track_saved_bits_mask;
  707. WARN_ON_ONCE(spte_ad_enabled(spte));
  708. WARN_ON_ONCE(!is_access_track_spte(spte));
  709. new_spte &= ~shadow_acc_track_mask;
  710. new_spte &= ~(shadow_acc_track_saved_bits_mask <<
  711. shadow_acc_track_saved_bits_shift);
  712. new_spte |= saved_bits;
  713. return new_spte;
  714. }
  715. /* Returns the Accessed status of the PTE and resets it at the same time. */
  716. static bool mmu_spte_age(u64 *sptep)
  717. {
  718. u64 spte = mmu_spte_get_lockless(sptep);
  719. if (!is_accessed_spte(spte))
  720. return false;
  721. if (spte_ad_enabled(spte)) {
  722. clear_bit((ffs(shadow_accessed_mask) - 1),
  723. (unsigned long *)sptep);
  724. } else {
  725. /*
  726. * Capture the dirty status of the page, so that it doesn't get
  727. * lost when the SPTE is marked for access tracking.
  728. */
  729. if (is_writable_pte(spte))
  730. kvm_set_pfn_dirty(spte_to_pfn(spte));
  731. spte = mark_spte_for_access_track(spte);
  732. mmu_spte_update_no_track(sptep, spte);
  733. }
  734. return true;
  735. }
  736. static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
  737. {
  738. /*
  739. * Prevent page table teardown by making any free-er wait during
  740. * kvm_flush_remote_tlbs() IPI to all active vcpus.
  741. */
  742. local_irq_disable();
  743. /*
  744. * Make sure a following spte read is not reordered ahead of the write
  745. * to vcpu->mode.
  746. */
  747. smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
  748. }
  749. static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
  750. {
  751. /*
  752. * Make sure the write to vcpu->mode is not reordered in front of
  753. * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
  754. * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
  755. */
  756. smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
  757. local_irq_enable();
  758. }
  759. static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
  760. struct kmem_cache *base_cache, int min)
  761. {
  762. void *obj;
  763. if (cache->nobjs >= min)
  764. return 0;
  765. while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
  766. obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
  767. if (!obj)
  768. return cache->nobjs >= min ? 0 : -ENOMEM;
  769. cache->objects[cache->nobjs++] = obj;
  770. }
  771. return 0;
  772. }
  773. static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
  774. {
  775. return cache->nobjs;
  776. }
  777. static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
  778. struct kmem_cache *cache)
  779. {
  780. while (mc->nobjs)
  781. kmem_cache_free(cache, mc->objects[--mc->nobjs]);
  782. }
  783. static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
  784. int min)
  785. {
  786. void *page;
  787. if (cache->nobjs >= min)
  788. return 0;
  789. while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
  790. page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
  791. if (!page)
  792. return cache->nobjs >= min ? 0 : -ENOMEM;
  793. cache->objects[cache->nobjs++] = page;
  794. }
  795. return 0;
  796. }
  797. static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
  798. {
  799. while (mc->nobjs)
  800. free_page((unsigned long)mc->objects[--mc->nobjs]);
  801. }
  802. static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
  803. {
  804. int r;
  805. r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
  806. pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
  807. if (r)
  808. goto out;
  809. r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
  810. if (r)
  811. goto out;
  812. r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
  813. mmu_page_header_cache, 4);
  814. out:
  815. return r;
  816. }
  817. static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
  818. {
  819. mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
  820. pte_list_desc_cache);
  821. mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
  822. mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
  823. mmu_page_header_cache);
  824. }
  825. static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
  826. {
  827. void *p;
  828. BUG_ON(!mc->nobjs);
  829. p = mc->objects[--mc->nobjs];
  830. return p;
  831. }
  832. static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
  833. {
  834. return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
  835. }
  836. static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
  837. {
  838. kmem_cache_free(pte_list_desc_cache, pte_list_desc);
  839. }
  840. static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
  841. {
  842. if (!sp->role.direct)
  843. return sp->gfns[index];
  844. return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
  845. }
  846. static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
  847. {
  848. if (sp->role.direct)
  849. BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
  850. else
  851. sp->gfns[index] = gfn;
  852. }
  853. /*
  854. * Return the pointer to the large page information for a given gfn,
  855. * handling slots that are not large page aligned.
  856. */
  857. static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
  858. struct kvm_memory_slot *slot,
  859. int level)
  860. {
  861. unsigned long idx;
  862. idx = gfn_to_index(gfn, slot->base_gfn, level);
  863. return &slot->arch.lpage_info[level - 2][idx];
  864. }
  865. static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
  866. gfn_t gfn, int count)
  867. {
  868. struct kvm_lpage_info *linfo;
  869. int i;
  870. for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  871. linfo = lpage_info_slot(gfn, slot, i);
  872. linfo->disallow_lpage += count;
  873. WARN_ON(linfo->disallow_lpage < 0);
  874. }
  875. }
  876. void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
  877. {
  878. update_gfn_disallow_lpage_count(slot, gfn, 1);
  879. }
  880. void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
  881. {
  882. update_gfn_disallow_lpage_count(slot, gfn, -1);
  883. }
  884. static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  885. {
  886. struct kvm_memslots *slots;
  887. struct kvm_memory_slot *slot;
  888. gfn_t gfn;
  889. kvm->arch.indirect_shadow_pages++;
  890. gfn = sp->gfn;
  891. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  892. slot = __gfn_to_memslot(slots, gfn);
  893. /* the non-leaf shadow pages are keeping readonly. */
  894. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  895. return kvm_slot_page_track_add_page(kvm, slot, gfn,
  896. KVM_PAGE_TRACK_WRITE);
  897. kvm_mmu_gfn_disallow_lpage(slot, gfn);
  898. }
  899. static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  900. {
  901. struct kvm_memslots *slots;
  902. struct kvm_memory_slot *slot;
  903. gfn_t gfn;
  904. kvm->arch.indirect_shadow_pages--;
  905. gfn = sp->gfn;
  906. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  907. slot = __gfn_to_memslot(slots, gfn);
  908. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  909. return kvm_slot_page_track_remove_page(kvm, slot, gfn,
  910. KVM_PAGE_TRACK_WRITE);
  911. kvm_mmu_gfn_allow_lpage(slot, gfn);
  912. }
  913. static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
  914. struct kvm_memory_slot *slot)
  915. {
  916. struct kvm_lpage_info *linfo;
  917. if (slot) {
  918. linfo = lpage_info_slot(gfn, slot, level);
  919. return !!linfo->disallow_lpage;
  920. }
  921. return true;
  922. }
  923. static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
  924. int level)
  925. {
  926. struct kvm_memory_slot *slot;
  927. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  928. return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
  929. }
  930. static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
  931. {
  932. unsigned long page_size;
  933. int i, ret = 0;
  934. page_size = kvm_host_page_size(kvm, gfn);
  935. for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  936. if (page_size >= KVM_HPAGE_SIZE(i))
  937. ret = i;
  938. else
  939. break;
  940. }
  941. return ret;
  942. }
  943. static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
  944. bool no_dirty_log)
  945. {
  946. if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
  947. return false;
  948. if (no_dirty_log && slot->dirty_bitmap)
  949. return false;
  950. return true;
  951. }
  952. static struct kvm_memory_slot *
  953. gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
  954. bool no_dirty_log)
  955. {
  956. struct kvm_memory_slot *slot;
  957. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  958. if (!memslot_valid_for_gpte(slot, no_dirty_log))
  959. slot = NULL;
  960. return slot;
  961. }
  962. static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
  963. bool *force_pt_level)
  964. {
  965. int host_level, level, max_level;
  966. struct kvm_memory_slot *slot;
  967. if (unlikely(*force_pt_level))
  968. return PT_PAGE_TABLE_LEVEL;
  969. slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
  970. *force_pt_level = !memslot_valid_for_gpte(slot, true);
  971. if (unlikely(*force_pt_level))
  972. return PT_PAGE_TABLE_LEVEL;
  973. host_level = host_mapping_level(vcpu->kvm, large_gfn);
  974. if (host_level == PT_PAGE_TABLE_LEVEL)
  975. return host_level;
  976. max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
  977. for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
  978. if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
  979. break;
  980. return level - 1;
  981. }
  982. /*
  983. * About rmap_head encoding:
  984. *
  985. * If the bit zero of rmap_head->val is clear, then it points to the only spte
  986. * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
  987. * pte_list_desc containing more mappings.
  988. */
  989. /*
  990. * Returns the number of pointers in the rmap chain, not counting the new one.
  991. */
  992. static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
  993. struct kvm_rmap_head *rmap_head)
  994. {
  995. struct pte_list_desc *desc;
  996. int i, count = 0;
  997. if (!rmap_head->val) {
  998. rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
  999. rmap_head->val = (unsigned long)spte;
  1000. } else if (!(rmap_head->val & 1)) {
  1001. rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
  1002. desc = mmu_alloc_pte_list_desc(vcpu);
  1003. desc->sptes[0] = (u64 *)rmap_head->val;
  1004. desc->sptes[1] = spte;
  1005. rmap_head->val = (unsigned long)desc | 1;
  1006. ++count;
  1007. } else {
  1008. rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
  1009. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1010. while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
  1011. desc = desc->more;
  1012. count += PTE_LIST_EXT;
  1013. }
  1014. if (desc->sptes[PTE_LIST_EXT-1]) {
  1015. desc->more = mmu_alloc_pte_list_desc(vcpu);
  1016. desc = desc->more;
  1017. }
  1018. for (i = 0; desc->sptes[i]; ++i)
  1019. ++count;
  1020. desc->sptes[i] = spte;
  1021. }
  1022. return count;
  1023. }
  1024. static void
  1025. pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
  1026. struct pte_list_desc *desc, int i,
  1027. struct pte_list_desc *prev_desc)
  1028. {
  1029. int j;
  1030. for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
  1031. ;
  1032. desc->sptes[i] = desc->sptes[j];
  1033. desc->sptes[j] = NULL;
  1034. if (j != 0)
  1035. return;
  1036. if (!prev_desc && !desc->more)
  1037. rmap_head->val = (unsigned long)desc->sptes[0];
  1038. else
  1039. if (prev_desc)
  1040. prev_desc->more = desc->more;
  1041. else
  1042. rmap_head->val = (unsigned long)desc->more | 1;
  1043. mmu_free_pte_list_desc(desc);
  1044. }
  1045. static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
  1046. {
  1047. struct pte_list_desc *desc;
  1048. struct pte_list_desc *prev_desc;
  1049. int i;
  1050. if (!rmap_head->val) {
  1051. pr_err("%s: %p 0->BUG\n", __func__, spte);
  1052. BUG();
  1053. } else if (!(rmap_head->val & 1)) {
  1054. rmap_printk("%s: %p 1->0\n", __func__, spte);
  1055. if ((u64 *)rmap_head->val != spte) {
  1056. pr_err("%s: %p 1->BUG\n", __func__, spte);
  1057. BUG();
  1058. }
  1059. rmap_head->val = 0;
  1060. } else {
  1061. rmap_printk("%s: %p many->many\n", __func__, spte);
  1062. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1063. prev_desc = NULL;
  1064. while (desc) {
  1065. for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
  1066. if (desc->sptes[i] == spte) {
  1067. pte_list_desc_remove_entry(rmap_head,
  1068. desc, i, prev_desc);
  1069. return;
  1070. }
  1071. }
  1072. prev_desc = desc;
  1073. desc = desc->more;
  1074. }
  1075. pr_err("%s: %p many->many\n", __func__, spte);
  1076. BUG();
  1077. }
  1078. }
  1079. static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
  1080. {
  1081. mmu_spte_clear_track_bits(sptep);
  1082. __pte_list_remove(sptep, rmap_head);
  1083. }
  1084. static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
  1085. struct kvm_memory_slot *slot)
  1086. {
  1087. unsigned long idx;
  1088. idx = gfn_to_index(gfn, slot->base_gfn, level);
  1089. return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
  1090. }
  1091. static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
  1092. struct kvm_mmu_page *sp)
  1093. {
  1094. struct kvm_memslots *slots;
  1095. struct kvm_memory_slot *slot;
  1096. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  1097. slot = __gfn_to_memslot(slots, gfn);
  1098. return __gfn_to_rmap(gfn, sp->role.level, slot);
  1099. }
  1100. static bool rmap_can_add(struct kvm_vcpu *vcpu)
  1101. {
  1102. struct kvm_mmu_memory_cache *cache;
  1103. cache = &vcpu->arch.mmu_pte_list_desc_cache;
  1104. return mmu_memory_cache_free_objects(cache);
  1105. }
  1106. static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
  1107. {
  1108. struct kvm_mmu_page *sp;
  1109. struct kvm_rmap_head *rmap_head;
  1110. sp = page_header(__pa(spte));
  1111. kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
  1112. rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
  1113. return pte_list_add(vcpu, spte, rmap_head);
  1114. }
  1115. static void rmap_remove(struct kvm *kvm, u64 *spte)
  1116. {
  1117. struct kvm_mmu_page *sp;
  1118. gfn_t gfn;
  1119. struct kvm_rmap_head *rmap_head;
  1120. sp = page_header(__pa(spte));
  1121. gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
  1122. rmap_head = gfn_to_rmap(kvm, gfn, sp);
  1123. __pte_list_remove(spte, rmap_head);
  1124. }
  1125. /*
  1126. * Used by the following functions to iterate through the sptes linked by a
  1127. * rmap. All fields are private and not assumed to be used outside.
  1128. */
  1129. struct rmap_iterator {
  1130. /* private fields */
  1131. struct pte_list_desc *desc; /* holds the sptep if not NULL */
  1132. int pos; /* index of the sptep */
  1133. };
  1134. /*
  1135. * Iteration must be started by this function. This should also be used after
  1136. * removing/dropping sptes from the rmap link because in such cases the
  1137. * information in the itererator may not be valid.
  1138. *
  1139. * Returns sptep if found, NULL otherwise.
  1140. */
  1141. static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
  1142. struct rmap_iterator *iter)
  1143. {
  1144. u64 *sptep;
  1145. if (!rmap_head->val)
  1146. return NULL;
  1147. if (!(rmap_head->val & 1)) {
  1148. iter->desc = NULL;
  1149. sptep = (u64 *)rmap_head->val;
  1150. goto out;
  1151. }
  1152. iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1153. iter->pos = 0;
  1154. sptep = iter->desc->sptes[iter->pos];
  1155. out:
  1156. BUG_ON(!is_shadow_present_pte(*sptep));
  1157. return sptep;
  1158. }
  1159. /*
  1160. * Must be used with a valid iterator: e.g. after rmap_get_first().
  1161. *
  1162. * Returns sptep if found, NULL otherwise.
  1163. */
  1164. static u64 *rmap_get_next(struct rmap_iterator *iter)
  1165. {
  1166. u64 *sptep;
  1167. if (iter->desc) {
  1168. if (iter->pos < PTE_LIST_EXT - 1) {
  1169. ++iter->pos;
  1170. sptep = iter->desc->sptes[iter->pos];
  1171. if (sptep)
  1172. goto out;
  1173. }
  1174. iter->desc = iter->desc->more;
  1175. if (iter->desc) {
  1176. iter->pos = 0;
  1177. /* desc->sptes[0] cannot be NULL */
  1178. sptep = iter->desc->sptes[iter->pos];
  1179. goto out;
  1180. }
  1181. }
  1182. return NULL;
  1183. out:
  1184. BUG_ON(!is_shadow_present_pte(*sptep));
  1185. return sptep;
  1186. }
  1187. #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
  1188. for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
  1189. _spte_; _spte_ = rmap_get_next(_iter_))
  1190. static void drop_spte(struct kvm *kvm, u64 *sptep)
  1191. {
  1192. if (mmu_spte_clear_track_bits(sptep))
  1193. rmap_remove(kvm, sptep);
  1194. }
  1195. static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
  1196. {
  1197. if (is_large_pte(*sptep)) {
  1198. WARN_ON(page_header(__pa(sptep))->role.level ==
  1199. PT_PAGE_TABLE_LEVEL);
  1200. drop_spte(kvm, sptep);
  1201. --kvm->stat.lpages;
  1202. return true;
  1203. }
  1204. return false;
  1205. }
  1206. static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
  1207. {
  1208. if (__drop_large_spte(vcpu->kvm, sptep))
  1209. kvm_flush_remote_tlbs(vcpu->kvm);
  1210. }
  1211. /*
  1212. * Write-protect on the specified @sptep, @pt_protect indicates whether
  1213. * spte write-protection is caused by protecting shadow page table.
  1214. *
  1215. * Note: write protection is difference between dirty logging and spte
  1216. * protection:
  1217. * - for dirty logging, the spte can be set to writable at anytime if
  1218. * its dirty bitmap is properly set.
  1219. * - for spte protection, the spte can be writable only after unsync-ing
  1220. * shadow page.
  1221. *
  1222. * Return true if tlb need be flushed.
  1223. */
  1224. static bool spte_write_protect(u64 *sptep, bool pt_protect)
  1225. {
  1226. u64 spte = *sptep;
  1227. if (!is_writable_pte(spte) &&
  1228. !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
  1229. return false;
  1230. rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
  1231. if (pt_protect)
  1232. spte &= ~SPTE_MMU_WRITEABLE;
  1233. spte = spte & ~PT_WRITABLE_MASK;
  1234. return mmu_spte_update(sptep, spte);
  1235. }
  1236. static bool __rmap_write_protect(struct kvm *kvm,
  1237. struct kvm_rmap_head *rmap_head,
  1238. bool pt_protect)
  1239. {
  1240. u64 *sptep;
  1241. struct rmap_iterator iter;
  1242. bool flush = false;
  1243. for_each_rmap_spte(rmap_head, &iter, sptep)
  1244. flush |= spte_write_protect(sptep, pt_protect);
  1245. return flush;
  1246. }
  1247. static bool spte_clear_dirty(u64 *sptep)
  1248. {
  1249. u64 spte = *sptep;
  1250. rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
  1251. spte &= ~shadow_dirty_mask;
  1252. return mmu_spte_update(sptep, spte);
  1253. }
  1254. static bool wrprot_ad_disabled_spte(u64 *sptep)
  1255. {
  1256. bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
  1257. (unsigned long *)sptep);
  1258. if (was_writable)
  1259. kvm_set_pfn_dirty(spte_to_pfn(*sptep));
  1260. return was_writable;
  1261. }
  1262. /*
  1263. * Gets the GFN ready for another round of dirty logging by clearing the
  1264. * - D bit on ad-enabled SPTEs, and
  1265. * - W bit on ad-disabled SPTEs.
  1266. * Returns true iff any D or W bits were cleared.
  1267. */
  1268. static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1269. {
  1270. u64 *sptep;
  1271. struct rmap_iterator iter;
  1272. bool flush = false;
  1273. for_each_rmap_spte(rmap_head, &iter, sptep)
  1274. if (spte_ad_enabled(*sptep))
  1275. flush |= spte_clear_dirty(sptep);
  1276. else
  1277. flush |= wrprot_ad_disabled_spte(sptep);
  1278. return flush;
  1279. }
  1280. static bool spte_set_dirty(u64 *sptep)
  1281. {
  1282. u64 spte = *sptep;
  1283. rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
  1284. spte |= shadow_dirty_mask;
  1285. return mmu_spte_update(sptep, spte);
  1286. }
  1287. static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1288. {
  1289. u64 *sptep;
  1290. struct rmap_iterator iter;
  1291. bool flush = false;
  1292. for_each_rmap_spte(rmap_head, &iter, sptep)
  1293. if (spte_ad_enabled(*sptep))
  1294. flush |= spte_set_dirty(sptep);
  1295. return flush;
  1296. }
  1297. /**
  1298. * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
  1299. * @kvm: kvm instance
  1300. * @slot: slot to protect
  1301. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1302. * @mask: indicates which pages we should protect
  1303. *
  1304. * Used when we do not need to care about huge page mappings: e.g. during dirty
  1305. * logging we do not have any such mappings.
  1306. */
  1307. static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
  1308. struct kvm_memory_slot *slot,
  1309. gfn_t gfn_offset, unsigned long mask)
  1310. {
  1311. struct kvm_rmap_head *rmap_head;
  1312. while (mask) {
  1313. rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1314. PT_PAGE_TABLE_LEVEL, slot);
  1315. __rmap_write_protect(kvm, rmap_head, false);
  1316. /* clear the first set bit */
  1317. mask &= mask - 1;
  1318. }
  1319. }
  1320. /**
  1321. * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
  1322. * protect the page if the D-bit isn't supported.
  1323. * @kvm: kvm instance
  1324. * @slot: slot to clear D-bit
  1325. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1326. * @mask: indicates which pages we should clear D-bit
  1327. *
  1328. * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
  1329. */
  1330. void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
  1331. struct kvm_memory_slot *slot,
  1332. gfn_t gfn_offset, unsigned long mask)
  1333. {
  1334. struct kvm_rmap_head *rmap_head;
  1335. while (mask) {
  1336. rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1337. PT_PAGE_TABLE_LEVEL, slot);
  1338. __rmap_clear_dirty(kvm, rmap_head);
  1339. /* clear the first set bit */
  1340. mask &= mask - 1;
  1341. }
  1342. }
  1343. EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
  1344. /**
  1345. * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
  1346. * PT level pages.
  1347. *
  1348. * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
  1349. * enable dirty logging for them.
  1350. *
  1351. * Used when we do not need to care about huge page mappings: e.g. during dirty
  1352. * logging we do not have any such mappings.
  1353. */
  1354. void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
  1355. struct kvm_memory_slot *slot,
  1356. gfn_t gfn_offset, unsigned long mask)
  1357. {
  1358. if (kvm_x86_ops->enable_log_dirty_pt_masked)
  1359. kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
  1360. mask);
  1361. else
  1362. kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
  1363. }
  1364. /**
  1365. * kvm_arch_write_log_dirty - emulate dirty page logging
  1366. * @vcpu: Guest mode vcpu
  1367. *
  1368. * Emulate arch specific page modification logging for the
  1369. * nested hypervisor
  1370. */
  1371. int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
  1372. {
  1373. if (kvm_x86_ops->write_log_dirty)
  1374. return kvm_x86_ops->write_log_dirty(vcpu);
  1375. return 0;
  1376. }
  1377. bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
  1378. struct kvm_memory_slot *slot, u64 gfn)
  1379. {
  1380. struct kvm_rmap_head *rmap_head;
  1381. int i;
  1382. bool write_protected = false;
  1383. for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  1384. rmap_head = __gfn_to_rmap(gfn, i, slot);
  1385. write_protected |= __rmap_write_protect(kvm, rmap_head, true);
  1386. }
  1387. return write_protected;
  1388. }
  1389. static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
  1390. {
  1391. struct kvm_memory_slot *slot;
  1392. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1393. return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
  1394. }
  1395. static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1396. {
  1397. u64 *sptep;
  1398. struct rmap_iterator iter;
  1399. bool flush = false;
  1400. while ((sptep = rmap_get_first(rmap_head, &iter))) {
  1401. rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
  1402. pte_list_remove(rmap_head, sptep);
  1403. flush = true;
  1404. }
  1405. return flush;
  1406. }
  1407. static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1408. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1409. unsigned long data)
  1410. {
  1411. return kvm_zap_rmapp(kvm, rmap_head);
  1412. }
  1413. static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1414. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1415. unsigned long data)
  1416. {
  1417. u64 *sptep;
  1418. struct rmap_iterator iter;
  1419. int need_flush = 0;
  1420. u64 new_spte;
  1421. pte_t *ptep = (pte_t *)data;
  1422. kvm_pfn_t new_pfn;
  1423. WARN_ON(pte_huge(*ptep));
  1424. new_pfn = pte_pfn(*ptep);
  1425. restart:
  1426. for_each_rmap_spte(rmap_head, &iter, sptep) {
  1427. rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
  1428. sptep, *sptep, gfn, level);
  1429. need_flush = 1;
  1430. if (pte_write(*ptep)) {
  1431. pte_list_remove(rmap_head, sptep);
  1432. goto restart;
  1433. } else {
  1434. new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
  1435. new_spte |= (u64)new_pfn << PAGE_SHIFT;
  1436. new_spte &= ~PT_WRITABLE_MASK;
  1437. new_spte &= ~SPTE_HOST_WRITEABLE;
  1438. new_spte = mark_spte_for_access_track(new_spte);
  1439. mmu_spte_clear_track_bits(sptep);
  1440. mmu_spte_set(sptep, new_spte);
  1441. }
  1442. }
  1443. if (need_flush)
  1444. kvm_flush_remote_tlbs(kvm);
  1445. return 0;
  1446. }
  1447. struct slot_rmap_walk_iterator {
  1448. /* input fields. */
  1449. struct kvm_memory_slot *slot;
  1450. gfn_t start_gfn;
  1451. gfn_t end_gfn;
  1452. int start_level;
  1453. int end_level;
  1454. /* output fields. */
  1455. gfn_t gfn;
  1456. struct kvm_rmap_head *rmap;
  1457. int level;
  1458. /* private field. */
  1459. struct kvm_rmap_head *end_rmap;
  1460. };
  1461. static void
  1462. rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
  1463. {
  1464. iterator->level = level;
  1465. iterator->gfn = iterator->start_gfn;
  1466. iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
  1467. iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
  1468. iterator->slot);
  1469. }
  1470. static void
  1471. slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
  1472. struct kvm_memory_slot *slot, int start_level,
  1473. int end_level, gfn_t start_gfn, gfn_t end_gfn)
  1474. {
  1475. iterator->slot = slot;
  1476. iterator->start_level = start_level;
  1477. iterator->end_level = end_level;
  1478. iterator->start_gfn = start_gfn;
  1479. iterator->end_gfn = end_gfn;
  1480. rmap_walk_init_level(iterator, iterator->start_level);
  1481. }
  1482. static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
  1483. {
  1484. return !!iterator->rmap;
  1485. }
  1486. static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
  1487. {
  1488. if (++iterator->rmap <= iterator->end_rmap) {
  1489. iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
  1490. return;
  1491. }
  1492. if (++iterator->level > iterator->end_level) {
  1493. iterator->rmap = NULL;
  1494. return;
  1495. }
  1496. rmap_walk_init_level(iterator, iterator->level);
  1497. }
  1498. #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
  1499. _start_gfn, _end_gfn, _iter_) \
  1500. for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
  1501. _end_level_, _start_gfn, _end_gfn); \
  1502. slot_rmap_walk_okay(_iter_); \
  1503. slot_rmap_walk_next(_iter_))
  1504. static int kvm_handle_hva_range(struct kvm *kvm,
  1505. unsigned long start,
  1506. unsigned long end,
  1507. unsigned long data,
  1508. int (*handler)(struct kvm *kvm,
  1509. struct kvm_rmap_head *rmap_head,
  1510. struct kvm_memory_slot *slot,
  1511. gfn_t gfn,
  1512. int level,
  1513. unsigned long data))
  1514. {
  1515. struct kvm_memslots *slots;
  1516. struct kvm_memory_slot *memslot;
  1517. struct slot_rmap_walk_iterator iterator;
  1518. int ret = 0;
  1519. int i;
  1520. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  1521. slots = __kvm_memslots(kvm, i);
  1522. kvm_for_each_memslot(memslot, slots) {
  1523. unsigned long hva_start, hva_end;
  1524. gfn_t gfn_start, gfn_end;
  1525. hva_start = max(start, memslot->userspace_addr);
  1526. hva_end = min(end, memslot->userspace_addr +
  1527. (memslot->npages << PAGE_SHIFT));
  1528. if (hva_start >= hva_end)
  1529. continue;
  1530. /*
  1531. * {gfn(page) | page intersects with [hva_start, hva_end)} =
  1532. * {gfn_start, gfn_start+1, ..., gfn_end-1}.
  1533. */
  1534. gfn_start = hva_to_gfn_memslot(hva_start, memslot);
  1535. gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
  1536. for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
  1537. PT_MAX_HUGEPAGE_LEVEL,
  1538. gfn_start, gfn_end - 1,
  1539. &iterator)
  1540. ret |= handler(kvm, iterator.rmap, memslot,
  1541. iterator.gfn, iterator.level, data);
  1542. }
  1543. }
  1544. return ret;
  1545. }
  1546. static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
  1547. unsigned long data,
  1548. int (*handler)(struct kvm *kvm,
  1549. struct kvm_rmap_head *rmap_head,
  1550. struct kvm_memory_slot *slot,
  1551. gfn_t gfn, int level,
  1552. unsigned long data))
  1553. {
  1554. return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
  1555. }
  1556. int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
  1557. {
  1558. return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
  1559. }
  1560. void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
  1561. {
  1562. kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
  1563. }
  1564. static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1565. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1566. unsigned long data)
  1567. {
  1568. u64 *sptep;
  1569. struct rmap_iterator uninitialized_var(iter);
  1570. int young = 0;
  1571. for_each_rmap_spte(rmap_head, &iter, sptep)
  1572. young |= mmu_spte_age(sptep);
  1573. trace_kvm_age_page(gfn, level, slot, young);
  1574. return young;
  1575. }
  1576. static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1577. struct kvm_memory_slot *slot, gfn_t gfn,
  1578. int level, unsigned long data)
  1579. {
  1580. u64 *sptep;
  1581. struct rmap_iterator iter;
  1582. for_each_rmap_spte(rmap_head, &iter, sptep)
  1583. if (is_accessed_spte(*sptep))
  1584. return 1;
  1585. return 0;
  1586. }
  1587. #define RMAP_RECYCLE_THRESHOLD 1000
  1588. static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
  1589. {
  1590. struct kvm_rmap_head *rmap_head;
  1591. struct kvm_mmu_page *sp;
  1592. sp = page_header(__pa(spte));
  1593. rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
  1594. kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
  1595. kvm_flush_remote_tlbs(vcpu->kvm);
  1596. }
  1597. int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
  1598. {
  1599. return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
  1600. }
  1601. int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
  1602. {
  1603. return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
  1604. }
  1605. #ifdef MMU_DEBUG
  1606. static int is_empty_shadow_page(u64 *spt)
  1607. {
  1608. u64 *pos;
  1609. u64 *end;
  1610. for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
  1611. if (is_shadow_present_pte(*pos)) {
  1612. printk(KERN_ERR "%s: %p %llx\n", __func__,
  1613. pos, *pos);
  1614. return 0;
  1615. }
  1616. return 1;
  1617. }
  1618. #endif
  1619. /*
  1620. * This value is the sum of all of the kvm instances's
  1621. * kvm->arch.n_used_mmu_pages values. We need a global,
  1622. * aggregate version in order to make the slab shrinker
  1623. * faster
  1624. */
  1625. static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
  1626. {
  1627. kvm->arch.n_used_mmu_pages += nr;
  1628. percpu_counter_add(&kvm_total_used_mmu_pages, nr);
  1629. }
  1630. static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
  1631. {
  1632. MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
  1633. hlist_del(&sp->hash_link);
  1634. list_del(&sp->link);
  1635. free_page((unsigned long)sp->spt);
  1636. if (!sp->role.direct)
  1637. free_page((unsigned long)sp->gfns);
  1638. kmem_cache_free(mmu_page_header_cache, sp);
  1639. }
  1640. static unsigned kvm_page_table_hashfn(gfn_t gfn)
  1641. {
  1642. return hash_64(gfn, KVM_MMU_HASH_SHIFT);
  1643. }
  1644. static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
  1645. struct kvm_mmu_page *sp, u64 *parent_pte)
  1646. {
  1647. if (!parent_pte)
  1648. return;
  1649. pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
  1650. }
  1651. static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
  1652. u64 *parent_pte)
  1653. {
  1654. __pte_list_remove(parent_pte, &sp->parent_ptes);
  1655. }
  1656. static void drop_parent_pte(struct kvm_mmu_page *sp,
  1657. u64 *parent_pte)
  1658. {
  1659. mmu_page_remove_parent_pte(sp, parent_pte);
  1660. mmu_spte_clear_no_track(parent_pte);
  1661. }
  1662. static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
  1663. {
  1664. struct kvm_mmu_page *sp;
  1665. sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
  1666. sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
  1667. if (!direct)
  1668. sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
  1669. set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
  1670. /*
  1671. * The active_mmu_pages list is the FIFO list, do not move the
  1672. * page until it is zapped. kvm_zap_obsolete_pages depends on
  1673. * this feature. See the comments in kvm_zap_obsolete_pages().
  1674. */
  1675. list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
  1676. kvm_mod_used_mmu_pages(vcpu->kvm, +1);
  1677. return sp;
  1678. }
  1679. static void mark_unsync(u64 *spte);
  1680. static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
  1681. {
  1682. u64 *sptep;
  1683. struct rmap_iterator iter;
  1684. for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
  1685. mark_unsync(sptep);
  1686. }
  1687. }
  1688. static void mark_unsync(u64 *spte)
  1689. {
  1690. struct kvm_mmu_page *sp;
  1691. unsigned int index;
  1692. sp = page_header(__pa(spte));
  1693. index = spte - sp->spt;
  1694. if (__test_and_set_bit(index, sp->unsync_child_bitmap))
  1695. return;
  1696. if (sp->unsync_children++)
  1697. return;
  1698. kvm_mmu_mark_parents_unsync(sp);
  1699. }
  1700. static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
  1701. struct kvm_mmu_page *sp)
  1702. {
  1703. return 0;
  1704. }
  1705. static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
  1706. {
  1707. }
  1708. static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
  1709. struct kvm_mmu_page *sp, u64 *spte,
  1710. const void *pte)
  1711. {
  1712. WARN_ON(1);
  1713. }
  1714. #define KVM_PAGE_ARRAY_NR 16
  1715. struct kvm_mmu_pages {
  1716. struct mmu_page_and_offset {
  1717. struct kvm_mmu_page *sp;
  1718. unsigned int idx;
  1719. } page[KVM_PAGE_ARRAY_NR];
  1720. unsigned int nr;
  1721. };
  1722. static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
  1723. int idx)
  1724. {
  1725. int i;
  1726. if (sp->unsync)
  1727. for (i=0; i < pvec->nr; i++)
  1728. if (pvec->page[i].sp == sp)
  1729. return 0;
  1730. pvec->page[pvec->nr].sp = sp;
  1731. pvec->page[pvec->nr].idx = idx;
  1732. pvec->nr++;
  1733. return (pvec->nr == KVM_PAGE_ARRAY_NR);
  1734. }
  1735. static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
  1736. {
  1737. --sp->unsync_children;
  1738. WARN_ON((int)sp->unsync_children < 0);
  1739. __clear_bit(idx, sp->unsync_child_bitmap);
  1740. }
  1741. static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
  1742. struct kvm_mmu_pages *pvec)
  1743. {
  1744. int i, ret, nr_unsync_leaf = 0;
  1745. for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
  1746. struct kvm_mmu_page *child;
  1747. u64 ent = sp->spt[i];
  1748. if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
  1749. clear_unsync_child_bit(sp, i);
  1750. continue;
  1751. }
  1752. child = page_header(ent & PT64_BASE_ADDR_MASK);
  1753. if (child->unsync_children) {
  1754. if (mmu_pages_add(pvec, child, i))
  1755. return -ENOSPC;
  1756. ret = __mmu_unsync_walk(child, pvec);
  1757. if (!ret) {
  1758. clear_unsync_child_bit(sp, i);
  1759. continue;
  1760. } else if (ret > 0) {
  1761. nr_unsync_leaf += ret;
  1762. } else
  1763. return ret;
  1764. } else if (child->unsync) {
  1765. nr_unsync_leaf++;
  1766. if (mmu_pages_add(pvec, child, i))
  1767. return -ENOSPC;
  1768. } else
  1769. clear_unsync_child_bit(sp, i);
  1770. }
  1771. return nr_unsync_leaf;
  1772. }
  1773. #define INVALID_INDEX (-1)
  1774. static int mmu_unsync_walk(struct kvm_mmu_page *sp,
  1775. struct kvm_mmu_pages *pvec)
  1776. {
  1777. pvec->nr = 0;
  1778. if (!sp->unsync_children)
  1779. return 0;
  1780. mmu_pages_add(pvec, sp, INVALID_INDEX);
  1781. return __mmu_unsync_walk(sp, pvec);
  1782. }
  1783. static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  1784. {
  1785. WARN_ON(!sp->unsync);
  1786. trace_kvm_mmu_sync_page(sp);
  1787. sp->unsync = 0;
  1788. --kvm->stat.mmu_unsync;
  1789. }
  1790. static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  1791. struct list_head *invalid_list);
  1792. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  1793. struct list_head *invalid_list);
  1794. /*
  1795. * NOTE: we should pay more attention on the zapped-obsolete page
  1796. * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
  1797. * since it has been deleted from active_mmu_pages but still can be found
  1798. * at hast list.
  1799. *
  1800. * for_each_valid_sp() has skipped that kind of pages.
  1801. */
  1802. #define for_each_valid_sp(_kvm, _sp, _gfn) \
  1803. hlist_for_each_entry(_sp, \
  1804. &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
  1805. if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
  1806. } else
  1807. #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
  1808. for_each_valid_sp(_kvm, _sp, _gfn) \
  1809. if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
  1810. /* @sp->gfn should be write-protected at the call site */
  1811. static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  1812. struct list_head *invalid_list)
  1813. {
  1814. if (sp->role.cr4_pae != !!is_pae(vcpu)
  1815. || vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
  1816. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
  1817. return false;
  1818. }
  1819. return true;
  1820. }
  1821. static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
  1822. struct list_head *invalid_list,
  1823. bool remote_flush, bool local_flush)
  1824. {
  1825. if (!list_empty(invalid_list)) {
  1826. kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
  1827. return;
  1828. }
  1829. if (remote_flush)
  1830. kvm_flush_remote_tlbs(vcpu->kvm);
  1831. else if (local_flush)
  1832. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  1833. }
  1834. #ifdef CONFIG_KVM_MMU_AUDIT
  1835. #include "mmu_audit.c"
  1836. #else
  1837. static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
  1838. static void mmu_audit_disable(void) { }
  1839. #endif
  1840. static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  1841. {
  1842. return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
  1843. }
  1844. static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  1845. struct list_head *invalid_list)
  1846. {
  1847. kvm_unlink_unsync_page(vcpu->kvm, sp);
  1848. return __kvm_sync_page(vcpu, sp, invalid_list);
  1849. }
  1850. /* @gfn should be write-protected at the call site */
  1851. static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
  1852. struct list_head *invalid_list)
  1853. {
  1854. struct kvm_mmu_page *s;
  1855. bool ret = false;
  1856. for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
  1857. if (!s->unsync)
  1858. continue;
  1859. WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
  1860. ret |= kvm_sync_page(vcpu, s, invalid_list);
  1861. }
  1862. return ret;
  1863. }
  1864. struct mmu_page_path {
  1865. struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
  1866. unsigned int idx[PT64_ROOT_MAX_LEVEL];
  1867. };
  1868. #define for_each_sp(pvec, sp, parents, i) \
  1869. for (i = mmu_pages_first(&pvec, &parents); \
  1870. i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
  1871. i = mmu_pages_next(&pvec, &parents, i))
  1872. static int mmu_pages_next(struct kvm_mmu_pages *pvec,
  1873. struct mmu_page_path *parents,
  1874. int i)
  1875. {
  1876. int n;
  1877. for (n = i+1; n < pvec->nr; n++) {
  1878. struct kvm_mmu_page *sp = pvec->page[n].sp;
  1879. unsigned idx = pvec->page[n].idx;
  1880. int level = sp->role.level;
  1881. parents->idx[level-1] = idx;
  1882. if (level == PT_PAGE_TABLE_LEVEL)
  1883. break;
  1884. parents->parent[level-2] = sp;
  1885. }
  1886. return n;
  1887. }
  1888. static int mmu_pages_first(struct kvm_mmu_pages *pvec,
  1889. struct mmu_page_path *parents)
  1890. {
  1891. struct kvm_mmu_page *sp;
  1892. int level;
  1893. if (pvec->nr == 0)
  1894. return 0;
  1895. WARN_ON(pvec->page[0].idx != INVALID_INDEX);
  1896. sp = pvec->page[0].sp;
  1897. level = sp->role.level;
  1898. WARN_ON(level == PT_PAGE_TABLE_LEVEL);
  1899. parents->parent[level-2] = sp;
  1900. /* Also set up a sentinel. Further entries in pvec are all
  1901. * children of sp, so this element is never overwritten.
  1902. */
  1903. parents->parent[level-1] = NULL;
  1904. return mmu_pages_next(pvec, parents, 0);
  1905. }
  1906. static void mmu_pages_clear_parents(struct mmu_page_path *parents)
  1907. {
  1908. struct kvm_mmu_page *sp;
  1909. unsigned int level = 0;
  1910. do {
  1911. unsigned int idx = parents->idx[level];
  1912. sp = parents->parent[level];
  1913. if (!sp)
  1914. return;
  1915. WARN_ON(idx == INVALID_INDEX);
  1916. clear_unsync_child_bit(sp, idx);
  1917. level++;
  1918. } while (!sp->unsync_children);
  1919. }
  1920. static void mmu_sync_children(struct kvm_vcpu *vcpu,
  1921. struct kvm_mmu_page *parent)
  1922. {
  1923. int i;
  1924. struct kvm_mmu_page *sp;
  1925. struct mmu_page_path parents;
  1926. struct kvm_mmu_pages pages;
  1927. LIST_HEAD(invalid_list);
  1928. bool flush = false;
  1929. while (mmu_unsync_walk(parent, &pages)) {
  1930. bool protected = false;
  1931. for_each_sp(pages, sp, parents, i)
  1932. protected |= rmap_write_protect(vcpu, sp->gfn);
  1933. if (protected) {
  1934. kvm_flush_remote_tlbs(vcpu->kvm);
  1935. flush = false;
  1936. }
  1937. for_each_sp(pages, sp, parents, i) {
  1938. flush |= kvm_sync_page(vcpu, sp, &invalid_list);
  1939. mmu_pages_clear_parents(&parents);
  1940. }
  1941. if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
  1942. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  1943. cond_resched_lock(&vcpu->kvm->mmu_lock);
  1944. flush = false;
  1945. }
  1946. }
  1947. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  1948. }
  1949. static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
  1950. {
  1951. atomic_set(&sp->write_flooding_count, 0);
  1952. }
  1953. static void clear_sp_write_flooding_count(u64 *spte)
  1954. {
  1955. struct kvm_mmu_page *sp = page_header(__pa(spte));
  1956. __clear_sp_write_flooding_count(sp);
  1957. }
  1958. static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
  1959. gfn_t gfn,
  1960. gva_t gaddr,
  1961. unsigned level,
  1962. int direct,
  1963. unsigned access)
  1964. {
  1965. union kvm_mmu_page_role role;
  1966. unsigned quadrant;
  1967. struct kvm_mmu_page *sp;
  1968. bool need_sync = false;
  1969. bool flush = false;
  1970. int collisions = 0;
  1971. LIST_HEAD(invalid_list);
  1972. role = vcpu->arch.mmu->mmu_role.base;
  1973. role.level = level;
  1974. role.direct = direct;
  1975. if (role.direct)
  1976. role.cr4_pae = 0;
  1977. role.access = access;
  1978. if (!vcpu->arch.mmu->direct_map
  1979. && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
  1980. quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
  1981. quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
  1982. role.quadrant = quadrant;
  1983. }
  1984. for_each_valid_sp(vcpu->kvm, sp, gfn) {
  1985. if (sp->gfn != gfn) {
  1986. collisions++;
  1987. continue;
  1988. }
  1989. if (!need_sync && sp->unsync)
  1990. need_sync = true;
  1991. if (sp->role.word != role.word)
  1992. continue;
  1993. if (sp->unsync) {
  1994. /* The page is good, but __kvm_sync_page might still end
  1995. * up zapping it. If so, break in order to rebuild it.
  1996. */
  1997. if (!__kvm_sync_page(vcpu, sp, &invalid_list))
  1998. break;
  1999. WARN_ON(!list_empty(&invalid_list));
  2000. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  2001. }
  2002. if (sp->unsync_children)
  2003. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  2004. __clear_sp_write_flooding_count(sp);
  2005. trace_kvm_mmu_get_page(sp, false);
  2006. goto out;
  2007. }
  2008. ++vcpu->kvm->stat.mmu_cache_miss;
  2009. sp = kvm_mmu_alloc_page(vcpu, direct);
  2010. sp->gfn = gfn;
  2011. sp->role = role;
  2012. hlist_add_head(&sp->hash_link,
  2013. &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
  2014. if (!direct) {
  2015. /*
  2016. * we should do write protection before syncing pages
  2017. * otherwise the content of the synced shadow page may
  2018. * be inconsistent with guest page table.
  2019. */
  2020. account_shadowed(vcpu->kvm, sp);
  2021. if (level == PT_PAGE_TABLE_LEVEL &&
  2022. rmap_write_protect(vcpu, gfn))
  2023. kvm_flush_remote_tlbs(vcpu->kvm);
  2024. if (level > PT_PAGE_TABLE_LEVEL && need_sync)
  2025. flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
  2026. }
  2027. sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
  2028. clear_page(sp->spt);
  2029. trace_kvm_mmu_get_page(sp, true);
  2030. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  2031. out:
  2032. if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
  2033. vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
  2034. return sp;
  2035. }
  2036. static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
  2037. struct kvm_vcpu *vcpu, hpa_t root,
  2038. u64 addr)
  2039. {
  2040. iterator->addr = addr;
  2041. iterator->shadow_addr = root;
  2042. iterator->level = vcpu->arch.mmu->shadow_root_level;
  2043. if (iterator->level == PT64_ROOT_4LEVEL &&
  2044. vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
  2045. !vcpu->arch.mmu->direct_map)
  2046. --iterator->level;
  2047. if (iterator->level == PT32E_ROOT_LEVEL) {
  2048. /*
  2049. * prev_root is currently only used for 64-bit hosts. So only
  2050. * the active root_hpa is valid here.
  2051. */
  2052. BUG_ON(root != vcpu->arch.mmu->root_hpa);
  2053. iterator->shadow_addr
  2054. = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
  2055. iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
  2056. --iterator->level;
  2057. if (!iterator->shadow_addr)
  2058. iterator->level = 0;
  2059. }
  2060. }
  2061. static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
  2062. struct kvm_vcpu *vcpu, u64 addr)
  2063. {
  2064. shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
  2065. addr);
  2066. }
  2067. static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
  2068. {
  2069. if (iterator->level < PT_PAGE_TABLE_LEVEL)
  2070. return false;
  2071. iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
  2072. iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
  2073. return true;
  2074. }
  2075. static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
  2076. u64 spte)
  2077. {
  2078. if (is_last_spte(spte, iterator->level)) {
  2079. iterator->level = 0;
  2080. return;
  2081. }
  2082. iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
  2083. --iterator->level;
  2084. }
  2085. static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
  2086. {
  2087. __shadow_walk_next(iterator, *iterator->sptep);
  2088. }
  2089. static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
  2090. struct kvm_mmu_page *sp)
  2091. {
  2092. u64 spte;
  2093. BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
  2094. spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
  2095. shadow_user_mask | shadow_x_mask | shadow_me_mask;
  2096. if (sp_ad_disabled(sp))
  2097. spte |= shadow_acc_track_value;
  2098. else
  2099. spte |= shadow_accessed_mask;
  2100. mmu_spte_set(sptep, spte);
  2101. mmu_page_add_parent_pte(vcpu, sp, sptep);
  2102. if (sp->unsync_children || sp->unsync)
  2103. mark_unsync(sptep);
  2104. }
  2105. static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
  2106. unsigned direct_access)
  2107. {
  2108. if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
  2109. struct kvm_mmu_page *child;
  2110. /*
  2111. * For the direct sp, if the guest pte's dirty bit
  2112. * changed form clean to dirty, it will corrupt the
  2113. * sp's access: allow writable in the read-only sp,
  2114. * so we should update the spte at this point to get
  2115. * a new sp with the correct access.
  2116. */
  2117. child = page_header(*sptep & PT64_BASE_ADDR_MASK);
  2118. if (child->role.access == direct_access)
  2119. return;
  2120. drop_parent_pte(child, sptep);
  2121. kvm_flush_remote_tlbs(vcpu->kvm);
  2122. }
  2123. }
  2124. static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
  2125. u64 *spte)
  2126. {
  2127. u64 pte;
  2128. struct kvm_mmu_page *child;
  2129. pte = *spte;
  2130. if (is_shadow_present_pte(pte)) {
  2131. if (is_last_spte(pte, sp->role.level)) {
  2132. drop_spte(kvm, spte);
  2133. if (is_large_pte(pte))
  2134. --kvm->stat.lpages;
  2135. } else {
  2136. child = page_header(pte & PT64_BASE_ADDR_MASK);
  2137. drop_parent_pte(child, spte);
  2138. }
  2139. return true;
  2140. }
  2141. if (is_mmio_spte(pte))
  2142. mmu_spte_clear_no_track(spte);
  2143. return false;
  2144. }
  2145. static void kvm_mmu_page_unlink_children(struct kvm *kvm,
  2146. struct kvm_mmu_page *sp)
  2147. {
  2148. unsigned i;
  2149. for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
  2150. mmu_page_zap_pte(kvm, sp, sp->spt + i);
  2151. }
  2152. static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
  2153. {
  2154. u64 *sptep;
  2155. struct rmap_iterator iter;
  2156. while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
  2157. drop_parent_pte(sp, sptep);
  2158. }
  2159. static int mmu_zap_unsync_children(struct kvm *kvm,
  2160. struct kvm_mmu_page *parent,
  2161. struct list_head *invalid_list)
  2162. {
  2163. int i, zapped = 0;
  2164. struct mmu_page_path parents;
  2165. struct kvm_mmu_pages pages;
  2166. if (parent->role.level == PT_PAGE_TABLE_LEVEL)
  2167. return 0;
  2168. while (mmu_unsync_walk(parent, &pages)) {
  2169. struct kvm_mmu_page *sp;
  2170. for_each_sp(pages, sp, parents, i) {
  2171. kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2172. mmu_pages_clear_parents(&parents);
  2173. zapped++;
  2174. }
  2175. }
  2176. return zapped;
  2177. }
  2178. static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  2179. struct list_head *invalid_list)
  2180. {
  2181. int ret;
  2182. trace_kvm_mmu_prepare_zap_page(sp);
  2183. ++kvm->stat.mmu_shadow_zapped;
  2184. ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
  2185. kvm_mmu_page_unlink_children(kvm, sp);
  2186. kvm_mmu_unlink_parents(kvm, sp);
  2187. if (!sp->role.invalid && !sp->role.direct)
  2188. unaccount_shadowed(kvm, sp);
  2189. if (sp->unsync)
  2190. kvm_unlink_unsync_page(kvm, sp);
  2191. if (!sp->root_count) {
  2192. /* Count self */
  2193. ret++;
  2194. list_move(&sp->link, invalid_list);
  2195. kvm_mod_used_mmu_pages(kvm, -1);
  2196. } else {
  2197. list_move(&sp->link, &kvm->arch.active_mmu_pages);
  2198. /*
  2199. * The obsolete pages can not be used on any vcpus.
  2200. * See the comments in kvm_mmu_invalidate_zap_all_pages().
  2201. */
  2202. if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
  2203. kvm_reload_remote_mmus(kvm);
  2204. }
  2205. sp->role.invalid = 1;
  2206. return ret;
  2207. }
  2208. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  2209. struct list_head *invalid_list)
  2210. {
  2211. struct kvm_mmu_page *sp, *nsp;
  2212. if (list_empty(invalid_list))
  2213. return;
  2214. /*
  2215. * We need to make sure everyone sees our modifications to
  2216. * the page tables and see changes to vcpu->mode here. The barrier
  2217. * in the kvm_flush_remote_tlbs() achieves this. This pairs
  2218. * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
  2219. *
  2220. * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
  2221. * guest mode and/or lockless shadow page table walks.
  2222. */
  2223. kvm_flush_remote_tlbs(kvm);
  2224. list_for_each_entry_safe(sp, nsp, invalid_list, link) {
  2225. WARN_ON(!sp->role.invalid || sp->root_count);
  2226. kvm_mmu_free_page(sp);
  2227. }
  2228. }
  2229. static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
  2230. struct list_head *invalid_list)
  2231. {
  2232. struct kvm_mmu_page *sp;
  2233. if (list_empty(&kvm->arch.active_mmu_pages))
  2234. return false;
  2235. sp = list_last_entry(&kvm->arch.active_mmu_pages,
  2236. struct kvm_mmu_page, link);
  2237. return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2238. }
  2239. /*
  2240. * Changing the number of mmu pages allocated to the vm
  2241. * Note: if goal_nr_mmu_pages is too small, you will get dead lock
  2242. */
  2243. void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
  2244. {
  2245. LIST_HEAD(invalid_list);
  2246. spin_lock(&kvm->mmu_lock);
  2247. if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
  2248. /* Need to free some mmu pages to achieve the goal. */
  2249. while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
  2250. if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
  2251. break;
  2252. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2253. goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
  2254. }
  2255. kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
  2256. spin_unlock(&kvm->mmu_lock);
  2257. }
  2258. int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
  2259. {
  2260. struct kvm_mmu_page *sp;
  2261. LIST_HEAD(invalid_list);
  2262. int r;
  2263. pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
  2264. r = 0;
  2265. spin_lock(&kvm->mmu_lock);
  2266. for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
  2267. pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
  2268. sp->role.word);
  2269. r = 1;
  2270. kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
  2271. }
  2272. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2273. spin_unlock(&kvm->mmu_lock);
  2274. return r;
  2275. }
  2276. EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
  2277. static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
  2278. {
  2279. trace_kvm_mmu_unsync_page(sp);
  2280. ++vcpu->kvm->stat.mmu_unsync;
  2281. sp->unsync = 1;
  2282. kvm_mmu_mark_parents_unsync(sp);
  2283. }
  2284. static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
  2285. bool can_unsync)
  2286. {
  2287. struct kvm_mmu_page *sp;
  2288. if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
  2289. return true;
  2290. for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
  2291. if (!can_unsync)
  2292. return true;
  2293. if (sp->unsync)
  2294. continue;
  2295. WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
  2296. kvm_unsync_page(vcpu, sp);
  2297. }
  2298. /*
  2299. * We need to ensure that the marking of unsync pages is visible
  2300. * before the SPTE is updated to allow writes because
  2301. * kvm_mmu_sync_roots() checks the unsync flags without holding
  2302. * the MMU lock and so can race with this. If the SPTE was updated
  2303. * before the page had been marked as unsync-ed, something like the
  2304. * following could happen:
  2305. *
  2306. * CPU 1 CPU 2
  2307. * ---------------------------------------------------------------------
  2308. * 1.2 Host updates SPTE
  2309. * to be writable
  2310. * 2.1 Guest writes a GPTE for GVA X.
  2311. * (GPTE being in the guest page table shadowed
  2312. * by the SP from CPU 1.)
  2313. * This reads SPTE during the page table walk.
  2314. * Since SPTE.W is read as 1, there is no
  2315. * fault.
  2316. *
  2317. * 2.2 Guest issues TLB flush.
  2318. * That causes a VM Exit.
  2319. *
  2320. * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
  2321. * Since it is false, so it just returns.
  2322. *
  2323. * 2.4 Guest accesses GVA X.
  2324. * Since the mapping in the SP was not updated,
  2325. * so the old mapping for GVA X incorrectly
  2326. * gets used.
  2327. * 1.1 Host marks SP
  2328. * as unsync
  2329. * (sp->unsync = true)
  2330. *
  2331. * The write barrier below ensures that 1.1 happens before 1.2 and thus
  2332. * the situation in 2.4 does not arise. The implicit barrier in 2.2
  2333. * pairs with this write barrier.
  2334. */
  2335. smp_wmb();
  2336. return false;
  2337. }
  2338. static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
  2339. {
  2340. if (pfn_valid(pfn))
  2341. return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
  2342. /*
  2343. * Some reserved pages, such as those from NVDIMM
  2344. * DAX devices, are not for MMIO, and can be mapped
  2345. * with cached memory type for better performance.
  2346. * However, the above check misconceives those pages
  2347. * as MMIO, and results in KVM mapping them with UC
  2348. * memory type, which would hurt the performance.
  2349. * Therefore, we check the host memory type in addition
  2350. * and only treat UC/UC-/WC pages as MMIO.
  2351. */
  2352. (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
  2353. return true;
  2354. }
  2355. /* Bits which may be returned by set_spte() */
  2356. #define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
  2357. #define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
  2358. static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
  2359. unsigned pte_access, int level,
  2360. gfn_t gfn, kvm_pfn_t pfn, bool speculative,
  2361. bool can_unsync, bool host_writable)
  2362. {
  2363. u64 spte = 0;
  2364. int ret = 0;
  2365. struct kvm_mmu_page *sp;
  2366. if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
  2367. return 0;
  2368. sp = page_header(__pa(sptep));
  2369. if (sp_ad_disabled(sp))
  2370. spte |= shadow_acc_track_value;
  2371. /*
  2372. * For the EPT case, shadow_present_mask is 0 if hardware
  2373. * supports exec-only page table entries. In that case,
  2374. * ACC_USER_MASK and shadow_user_mask are used to represent
  2375. * read access. See FNAME(gpte_access) in paging_tmpl.h.
  2376. */
  2377. spte |= shadow_present_mask;
  2378. if (!speculative)
  2379. spte |= spte_shadow_accessed_mask(spte);
  2380. if (pte_access & ACC_EXEC_MASK)
  2381. spte |= shadow_x_mask;
  2382. else
  2383. spte |= shadow_nx_mask;
  2384. if (pte_access & ACC_USER_MASK)
  2385. spte |= shadow_user_mask;
  2386. if (level > PT_PAGE_TABLE_LEVEL)
  2387. spte |= PT_PAGE_SIZE_MASK;
  2388. if (tdp_enabled)
  2389. spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
  2390. kvm_is_mmio_pfn(pfn));
  2391. if (host_writable)
  2392. spte |= SPTE_HOST_WRITEABLE;
  2393. else
  2394. pte_access &= ~ACC_WRITE_MASK;
  2395. if (!kvm_is_mmio_pfn(pfn))
  2396. spte |= shadow_me_mask;
  2397. spte |= (u64)pfn << PAGE_SHIFT;
  2398. if (pte_access & ACC_WRITE_MASK) {
  2399. /*
  2400. * Other vcpu creates new sp in the window between
  2401. * mapping_level() and acquiring mmu-lock. We can
  2402. * allow guest to retry the access, the mapping can
  2403. * be fixed if guest refault.
  2404. */
  2405. if (level > PT_PAGE_TABLE_LEVEL &&
  2406. mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
  2407. goto done;
  2408. spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
  2409. /*
  2410. * Optimization: for pte sync, if spte was writable the hash
  2411. * lookup is unnecessary (and expensive). Write protection
  2412. * is responsibility of mmu_get_page / kvm_sync_page.
  2413. * Same reasoning can be applied to dirty page accounting.
  2414. */
  2415. if (!can_unsync && is_writable_pte(*sptep))
  2416. goto set_pte;
  2417. if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
  2418. pgprintk("%s: found shadow page for %llx, marking ro\n",
  2419. __func__, gfn);
  2420. ret |= SET_SPTE_WRITE_PROTECTED_PT;
  2421. pte_access &= ~ACC_WRITE_MASK;
  2422. spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
  2423. }
  2424. }
  2425. if (pte_access & ACC_WRITE_MASK) {
  2426. kvm_vcpu_mark_page_dirty(vcpu, gfn);
  2427. spte |= spte_shadow_dirty_mask(spte);
  2428. }
  2429. if (speculative)
  2430. spte = mark_spte_for_access_track(spte);
  2431. set_pte:
  2432. if (mmu_spte_update(sptep, spte))
  2433. ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
  2434. done:
  2435. return ret;
  2436. }
  2437. static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
  2438. int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
  2439. bool speculative, bool host_writable)
  2440. {
  2441. int was_rmapped = 0;
  2442. int rmap_count;
  2443. int set_spte_ret;
  2444. int ret = RET_PF_RETRY;
  2445. bool flush = false;
  2446. pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
  2447. *sptep, write_fault, gfn);
  2448. if (is_shadow_present_pte(*sptep)) {
  2449. /*
  2450. * If we overwrite a PTE page pointer with a 2MB PMD, unlink
  2451. * the parent of the now unreachable PTE.
  2452. */
  2453. if (level > PT_PAGE_TABLE_LEVEL &&
  2454. !is_large_pte(*sptep)) {
  2455. struct kvm_mmu_page *child;
  2456. u64 pte = *sptep;
  2457. child = page_header(pte & PT64_BASE_ADDR_MASK);
  2458. drop_parent_pte(child, sptep);
  2459. flush = true;
  2460. } else if (pfn != spte_to_pfn(*sptep)) {
  2461. pgprintk("hfn old %llx new %llx\n",
  2462. spte_to_pfn(*sptep), pfn);
  2463. drop_spte(vcpu->kvm, sptep);
  2464. flush = true;
  2465. } else
  2466. was_rmapped = 1;
  2467. }
  2468. set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
  2469. speculative, true, host_writable);
  2470. if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
  2471. if (write_fault)
  2472. ret = RET_PF_EMULATE;
  2473. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  2474. }
  2475. if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
  2476. kvm_flush_remote_tlbs(vcpu->kvm);
  2477. if (unlikely(is_mmio_spte(*sptep)))
  2478. ret = RET_PF_EMULATE;
  2479. pgprintk("%s: setting spte %llx\n", __func__, *sptep);
  2480. pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
  2481. is_large_pte(*sptep)? "2MB" : "4kB",
  2482. *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
  2483. *sptep, sptep);
  2484. if (!was_rmapped && is_large_pte(*sptep))
  2485. ++vcpu->kvm->stat.lpages;
  2486. if (is_shadow_present_pte(*sptep)) {
  2487. if (!was_rmapped) {
  2488. rmap_count = rmap_add(vcpu, sptep, gfn);
  2489. if (rmap_count > RMAP_RECYCLE_THRESHOLD)
  2490. rmap_recycle(vcpu, sptep, gfn);
  2491. }
  2492. }
  2493. kvm_release_pfn_clean(pfn);
  2494. return ret;
  2495. }
  2496. static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
  2497. bool no_dirty_log)
  2498. {
  2499. struct kvm_memory_slot *slot;
  2500. slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
  2501. if (!slot)
  2502. return KVM_PFN_ERR_FAULT;
  2503. return gfn_to_pfn_memslot_atomic(slot, gfn);
  2504. }
  2505. static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
  2506. struct kvm_mmu_page *sp,
  2507. u64 *start, u64 *end)
  2508. {
  2509. struct page *pages[PTE_PREFETCH_NUM];
  2510. struct kvm_memory_slot *slot;
  2511. unsigned access = sp->role.access;
  2512. int i, ret;
  2513. gfn_t gfn;
  2514. gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
  2515. slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
  2516. if (!slot)
  2517. return -1;
  2518. ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
  2519. if (ret <= 0)
  2520. return -1;
  2521. for (i = 0; i < ret; i++, gfn++, start++)
  2522. mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
  2523. page_to_pfn(pages[i]), true, true);
  2524. return 0;
  2525. }
  2526. static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
  2527. struct kvm_mmu_page *sp, u64 *sptep)
  2528. {
  2529. u64 *spte, *start = NULL;
  2530. int i;
  2531. WARN_ON(!sp->role.direct);
  2532. i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
  2533. spte = sp->spt + i;
  2534. for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
  2535. if (is_shadow_present_pte(*spte) || spte == sptep) {
  2536. if (!start)
  2537. continue;
  2538. if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
  2539. break;
  2540. start = NULL;
  2541. } else if (!start)
  2542. start = spte;
  2543. }
  2544. }
  2545. static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
  2546. {
  2547. struct kvm_mmu_page *sp;
  2548. sp = page_header(__pa(sptep));
  2549. /*
  2550. * Without accessed bits, there's no way to distinguish between
  2551. * actually accessed translations and prefetched, so disable pte
  2552. * prefetch if accessed bits aren't available.
  2553. */
  2554. if (sp_ad_disabled(sp))
  2555. return;
  2556. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  2557. return;
  2558. __direct_pte_prefetch(vcpu, sp, sptep);
  2559. }
  2560. static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
  2561. int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
  2562. {
  2563. struct kvm_shadow_walk_iterator iterator;
  2564. struct kvm_mmu_page *sp;
  2565. int emulate = 0;
  2566. gfn_t pseudo_gfn;
  2567. if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
  2568. return 0;
  2569. for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
  2570. if (iterator.level == level) {
  2571. emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
  2572. write, level, gfn, pfn, prefault,
  2573. map_writable);
  2574. direct_pte_prefetch(vcpu, iterator.sptep);
  2575. ++vcpu->stat.pf_fixed;
  2576. break;
  2577. }
  2578. drop_large_spte(vcpu, iterator.sptep);
  2579. if (!is_shadow_present_pte(*iterator.sptep)) {
  2580. u64 base_addr = iterator.addr;
  2581. base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
  2582. pseudo_gfn = base_addr >> PAGE_SHIFT;
  2583. sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
  2584. iterator.level - 1, 1, ACC_ALL);
  2585. link_shadow_page(vcpu, iterator.sptep, sp);
  2586. }
  2587. }
  2588. return emulate;
  2589. }
  2590. static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
  2591. {
  2592. send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
  2593. }
  2594. static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
  2595. {
  2596. /*
  2597. * Do not cache the mmio info caused by writing the readonly gfn
  2598. * into the spte otherwise read access on readonly gfn also can
  2599. * caused mmio page fault and treat it as mmio access.
  2600. */
  2601. if (pfn == KVM_PFN_ERR_RO_FAULT)
  2602. return RET_PF_EMULATE;
  2603. if (pfn == KVM_PFN_ERR_HWPOISON) {
  2604. kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
  2605. return RET_PF_RETRY;
  2606. }
  2607. return -EFAULT;
  2608. }
  2609. static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
  2610. gfn_t *gfnp, kvm_pfn_t *pfnp,
  2611. int *levelp)
  2612. {
  2613. kvm_pfn_t pfn = *pfnp;
  2614. gfn_t gfn = *gfnp;
  2615. int level = *levelp;
  2616. /*
  2617. * Check if it's a transparent hugepage. If this would be an
  2618. * hugetlbfs page, level wouldn't be set to
  2619. * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
  2620. * here.
  2621. */
  2622. if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
  2623. level == PT_PAGE_TABLE_LEVEL &&
  2624. PageTransCompoundMap(pfn_to_page(pfn)) &&
  2625. !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
  2626. unsigned long mask;
  2627. /*
  2628. * mmu_notifier_retry was successful and we hold the
  2629. * mmu_lock here, so the pmd can't become splitting
  2630. * from under us, and in turn
  2631. * __split_huge_page_refcount() can't run from under
  2632. * us and we can safely transfer the refcount from
  2633. * PG_tail to PG_head as we switch the pfn to tail to
  2634. * head.
  2635. */
  2636. *levelp = level = PT_DIRECTORY_LEVEL;
  2637. mask = KVM_PAGES_PER_HPAGE(level) - 1;
  2638. VM_BUG_ON((gfn & mask) != (pfn & mask));
  2639. if (pfn & mask) {
  2640. gfn &= ~mask;
  2641. *gfnp = gfn;
  2642. kvm_release_pfn_clean(pfn);
  2643. pfn &= ~mask;
  2644. kvm_get_pfn(pfn);
  2645. *pfnp = pfn;
  2646. }
  2647. }
  2648. }
  2649. static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
  2650. kvm_pfn_t pfn, unsigned access, int *ret_val)
  2651. {
  2652. /* The pfn is invalid, report the error! */
  2653. if (unlikely(is_error_pfn(pfn))) {
  2654. *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
  2655. return true;
  2656. }
  2657. if (unlikely(is_noslot_pfn(pfn)))
  2658. vcpu_cache_mmio_info(vcpu, gva, gfn, access);
  2659. return false;
  2660. }
  2661. static bool page_fault_can_be_fast(u32 error_code)
  2662. {
  2663. /*
  2664. * Do not fix the mmio spte with invalid generation number which
  2665. * need to be updated by slow page fault path.
  2666. */
  2667. if (unlikely(error_code & PFERR_RSVD_MASK))
  2668. return false;
  2669. /* See if the page fault is due to an NX violation */
  2670. if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
  2671. == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
  2672. return false;
  2673. /*
  2674. * #PF can be fast if:
  2675. * 1. The shadow page table entry is not present, which could mean that
  2676. * the fault is potentially caused by access tracking (if enabled).
  2677. * 2. The shadow page table entry is present and the fault
  2678. * is caused by write-protect, that means we just need change the W
  2679. * bit of the spte which can be done out of mmu-lock.
  2680. *
  2681. * However, if access tracking is disabled we know that a non-present
  2682. * page must be a genuine page fault where we have to create a new SPTE.
  2683. * So, if access tracking is disabled, we return true only for write
  2684. * accesses to a present page.
  2685. */
  2686. return shadow_acc_track_mask != 0 ||
  2687. ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
  2688. == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
  2689. }
  2690. /*
  2691. * Returns true if the SPTE was fixed successfully. Otherwise,
  2692. * someone else modified the SPTE from its original value.
  2693. */
  2694. static bool
  2695. fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  2696. u64 *sptep, u64 old_spte, u64 new_spte)
  2697. {
  2698. gfn_t gfn;
  2699. WARN_ON(!sp->role.direct);
  2700. /*
  2701. * Theoretically we could also set dirty bit (and flush TLB) here in
  2702. * order to eliminate unnecessary PML logging. See comments in
  2703. * set_spte. But fast_page_fault is very unlikely to happen with PML
  2704. * enabled, so we do not do this. This might result in the same GPA
  2705. * to be logged in PML buffer again when the write really happens, and
  2706. * eventually to be called by mark_page_dirty twice. But it's also no
  2707. * harm. This also avoids the TLB flush needed after setting dirty bit
  2708. * so non-PML cases won't be impacted.
  2709. *
  2710. * Compare with set_spte where instead shadow_dirty_mask is set.
  2711. */
  2712. if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
  2713. return false;
  2714. if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
  2715. /*
  2716. * The gfn of direct spte is stable since it is
  2717. * calculated by sp->gfn.
  2718. */
  2719. gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
  2720. kvm_vcpu_mark_page_dirty(vcpu, gfn);
  2721. }
  2722. return true;
  2723. }
  2724. static bool is_access_allowed(u32 fault_err_code, u64 spte)
  2725. {
  2726. if (fault_err_code & PFERR_FETCH_MASK)
  2727. return is_executable_pte(spte);
  2728. if (fault_err_code & PFERR_WRITE_MASK)
  2729. return is_writable_pte(spte);
  2730. /* Fault was on Read access */
  2731. return spte & PT_PRESENT_MASK;
  2732. }
  2733. /*
  2734. * Return value:
  2735. * - true: let the vcpu to access on the same address again.
  2736. * - false: let the real page fault path to fix it.
  2737. */
  2738. static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
  2739. u32 error_code)
  2740. {
  2741. struct kvm_shadow_walk_iterator iterator;
  2742. struct kvm_mmu_page *sp;
  2743. bool fault_handled = false;
  2744. u64 spte = 0ull;
  2745. uint retry_count = 0;
  2746. if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
  2747. return false;
  2748. if (!page_fault_can_be_fast(error_code))
  2749. return false;
  2750. walk_shadow_page_lockless_begin(vcpu);
  2751. do {
  2752. u64 new_spte;
  2753. for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
  2754. if (!is_shadow_present_pte(spte) ||
  2755. iterator.level < level)
  2756. break;
  2757. sp = page_header(__pa(iterator.sptep));
  2758. if (!is_last_spte(spte, sp->role.level))
  2759. break;
  2760. /*
  2761. * Check whether the memory access that caused the fault would
  2762. * still cause it if it were to be performed right now. If not,
  2763. * then this is a spurious fault caused by TLB lazily flushed,
  2764. * or some other CPU has already fixed the PTE after the
  2765. * current CPU took the fault.
  2766. *
  2767. * Need not check the access of upper level table entries since
  2768. * they are always ACC_ALL.
  2769. */
  2770. if (is_access_allowed(error_code, spte)) {
  2771. fault_handled = true;
  2772. break;
  2773. }
  2774. new_spte = spte;
  2775. if (is_access_track_spte(spte))
  2776. new_spte = restore_acc_track_spte(new_spte);
  2777. /*
  2778. * Currently, to simplify the code, write-protection can
  2779. * be removed in the fast path only if the SPTE was
  2780. * write-protected for dirty-logging or access tracking.
  2781. */
  2782. if ((error_code & PFERR_WRITE_MASK) &&
  2783. spte_can_locklessly_be_made_writable(spte))
  2784. {
  2785. new_spte |= PT_WRITABLE_MASK;
  2786. /*
  2787. * Do not fix write-permission on the large spte. Since
  2788. * we only dirty the first page into the dirty-bitmap in
  2789. * fast_pf_fix_direct_spte(), other pages are missed
  2790. * if its slot has dirty logging enabled.
  2791. *
  2792. * Instead, we let the slow page fault path create a
  2793. * normal spte to fix the access.
  2794. *
  2795. * See the comments in kvm_arch_commit_memory_region().
  2796. */
  2797. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  2798. break;
  2799. }
  2800. /* Verify that the fault can be handled in the fast path */
  2801. if (new_spte == spte ||
  2802. !is_access_allowed(error_code, new_spte))
  2803. break;
  2804. /*
  2805. * Currently, fast page fault only works for direct mapping
  2806. * since the gfn is not stable for indirect shadow page. See
  2807. * Documentation/virtual/kvm/locking.txt to get more detail.
  2808. */
  2809. fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
  2810. iterator.sptep, spte,
  2811. new_spte);
  2812. if (fault_handled)
  2813. break;
  2814. if (++retry_count > 4) {
  2815. printk_once(KERN_WARNING
  2816. "kvm: Fast #PF retrying more than 4 times.\n");
  2817. break;
  2818. }
  2819. } while (true);
  2820. trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
  2821. spte, fault_handled);
  2822. walk_shadow_page_lockless_end(vcpu);
  2823. return fault_handled;
  2824. }
  2825. static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
  2826. gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
  2827. static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
  2828. static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
  2829. gfn_t gfn, bool prefault)
  2830. {
  2831. int r;
  2832. int level;
  2833. bool force_pt_level = false;
  2834. kvm_pfn_t pfn;
  2835. unsigned long mmu_seq;
  2836. bool map_writable, write = error_code & PFERR_WRITE_MASK;
  2837. level = mapping_level(vcpu, gfn, &force_pt_level);
  2838. if (likely(!force_pt_level)) {
  2839. /*
  2840. * This path builds a PAE pagetable - so we can map
  2841. * 2mb pages at maximum. Therefore check if the level
  2842. * is larger than that.
  2843. */
  2844. if (level > PT_DIRECTORY_LEVEL)
  2845. level = PT_DIRECTORY_LEVEL;
  2846. gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
  2847. }
  2848. if (fast_page_fault(vcpu, v, level, error_code))
  2849. return RET_PF_RETRY;
  2850. mmu_seq = vcpu->kvm->mmu_notifier_seq;
  2851. smp_rmb();
  2852. if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
  2853. return RET_PF_RETRY;
  2854. if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
  2855. return r;
  2856. spin_lock(&vcpu->kvm->mmu_lock);
  2857. if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
  2858. goto out_unlock;
  2859. if (make_mmu_pages_available(vcpu) < 0)
  2860. goto out_unlock;
  2861. if (likely(!force_pt_level))
  2862. transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
  2863. r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
  2864. spin_unlock(&vcpu->kvm->mmu_lock);
  2865. return r;
  2866. out_unlock:
  2867. spin_unlock(&vcpu->kvm->mmu_lock);
  2868. kvm_release_pfn_clean(pfn);
  2869. return RET_PF_RETRY;
  2870. }
  2871. static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
  2872. struct list_head *invalid_list)
  2873. {
  2874. struct kvm_mmu_page *sp;
  2875. if (!VALID_PAGE(*root_hpa))
  2876. return;
  2877. sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
  2878. --sp->root_count;
  2879. if (!sp->root_count && sp->role.invalid)
  2880. kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2881. *root_hpa = INVALID_PAGE;
  2882. }
  2883. /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
  2884. void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  2885. ulong roots_to_free)
  2886. {
  2887. int i;
  2888. LIST_HEAD(invalid_list);
  2889. bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
  2890. BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
  2891. /* Before acquiring the MMU lock, see if we need to do any real work. */
  2892. if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
  2893. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  2894. if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
  2895. VALID_PAGE(mmu->prev_roots[i].hpa))
  2896. break;
  2897. if (i == KVM_MMU_NUM_PREV_ROOTS)
  2898. return;
  2899. }
  2900. spin_lock(&vcpu->kvm->mmu_lock);
  2901. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  2902. if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
  2903. mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
  2904. &invalid_list);
  2905. if (free_active_root) {
  2906. if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
  2907. (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
  2908. mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
  2909. &invalid_list);
  2910. } else {
  2911. for (i = 0; i < 4; ++i)
  2912. if (mmu->pae_root[i] != 0)
  2913. mmu_free_root_page(vcpu->kvm,
  2914. &mmu->pae_root[i],
  2915. &invalid_list);
  2916. mmu->root_hpa = INVALID_PAGE;
  2917. }
  2918. }
  2919. kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
  2920. spin_unlock(&vcpu->kvm->mmu_lock);
  2921. }
  2922. EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
  2923. static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
  2924. {
  2925. int ret = 0;
  2926. if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
  2927. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2928. ret = 1;
  2929. }
  2930. return ret;
  2931. }
  2932. static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
  2933. {
  2934. struct kvm_mmu_page *sp;
  2935. unsigned i;
  2936. if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
  2937. spin_lock(&vcpu->kvm->mmu_lock);
  2938. if(make_mmu_pages_available(vcpu) < 0) {
  2939. spin_unlock(&vcpu->kvm->mmu_lock);
  2940. return -ENOSPC;
  2941. }
  2942. sp = kvm_mmu_get_page(vcpu, 0, 0,
  2943. vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
  2944. ++sp->root_count;
  2945. spin_unlock(&vcpu->kvm->mmu_lock);
  2946. vcpu->arch.mmu->root_hpa = __pa(sp->spt);
  2947. } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
  2948. for (i = 0; i < 4; ++i) {
  2949. hpa_t root = vcpu->arch.mmu->pae_root[i];
  2950. MMU_WARN_ON(VALID_PAGE(root));
  2951. spin_lock(&vcpu->kvm->mmu_lock);
  2952. if (make_mmu_pages_available(vcpu) < 0) {
  2953. spin_unlock(&vcpu->kvm->mmu_lock);
  2954. return -ENOSPC;
  2955. }
  2956. sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
  2957. i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
  2958. root = __pa(sp->spt);
  2959. ++sp->root_count;
  2960. spin_unlock(&vcpu->kvm->mmu_lock);
  2961. vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
  2962. }
  2963. vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
  2964. } else
  2965. BUG();
  2966. return 0;
  2967. }
  2968. static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
  2969. {
  2970. struct kvm_mmu_page *sp;
  2971. u64 pdptr, pm_mask;
  2972. gfn_t root_gfn;
  2973. int i;
  2974. root_gfn = vcpu->arch.mmu->get_cr3(vcpu) >> PAGE_SHIFT;
  2975. if (mmu_check_root(vcpu, root_gfn))
  2976. return 1;
  2977. /*
  2978. * Do we shadow a long mode page table? If so we need to
  2979. * write-protect the guests page table root.
  2980. */
  2981. if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
  2982. hpa_t root = vcpu->arch.mmu->root_hpa;
  2983. MMU_WARN_ON(VALID_PAGE(root));
  2984. spin_lock(&vcpu->kvm->mmu_lock);
  2985. if (make_mmu_pages_available(vcpu) < 0) {
  2986. spin_unlock(&vcpu->kvm->mmu_lock);
  2987. return -ENOSPC;
  2988. }
  2989. sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
  2990. vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
  2991. root = __pa(sp->spt);
  2992. ++sp->root_count;
  2993. spin_unlock(&vcpu->kvm->mmu_lock);
  2994. vcpu->arch.mmu->root_hpa = root;
  2995. return 0;
  2996. }
  2997. /*
  2998. * We shadow a 32 bit page table. This may be a legacy 2-level
  2999. * or a PAE 3-level page table. In either case we need to be aware that
  3000. * the shadow page table may be a PAE or a long mode page table.
  3001. */
  3002. pm_mask = PT_PRESENT_MASK;
  3003. if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
  3004. pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
  3005. for (i = 0; i < 4; ++i) {
  3006. hpa_t root = vcpu->arch.mmu->pae_root[i];
  3007. MMU_WARN_ON(VALID_PAGE(root));
  3008. if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
  3009. pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
  3010. if (!(pdptr & PT_PRESENT_MASK)) {
  3011. vcpu->arch.mmu->pae_root[i] = 0;
  3012. continue;
  3013. }
  3014. root_gfn = pdptr >> PAGE_SHIFT;
  3015. if (mmu_check_root(vcpu, root_gfn))
  3016. return 1;
  3017. }
  3018. spin_lock(&vcpu->kvm->mmu_lock);
  3019. if (make_mmu_pages_available(vcpu) < 0) {
  3020. spin_unlock(&vcpu->kvm->mmu_lock);
  3021. return -ENOSPC;
  3022. }
  3023. sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
  3024. 0, ACC_ALL);
  3025. root = __pa(sp->spt);
  3026. ++sp->root_count;
  3027. spin_unlock(&vcpu->kvm->mmu_lock);
  3028. vcpu->arch.mmu->pae_root[i] = root | pm_mask;
  3029. }
  3030. vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
  3031. /*
  3032. * If we shadow a 32 bit page table with a long mode page
  3033. * table we enter this path.
  3034. */
  3035. if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
  3036. if (vcpu->arch.mmu->lm_root == NULL) {
  3037. /*
  3038. * The additional page necessary for this is only
  3039. * allocated on demand.
  3040. */
  3041. u64 *lm_root;
  3042. lm_root = (void*)get_zeroed_page(GFP_KERNEL);
  3043. if (lm_root == NULL)
  3044. return 1;
  3045. lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
  3046. vcpu->arch.mmu->lm_root = lm_root;
  3047. }
  3048. vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
  3049. }
  3050. return 0;
  3051. }
  3052. static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
  3053. {
  3054. if (vcpu->arch.mmu->direct_map)
  3055. return mmu_alloc_direct_roots(vcpu);
  3056. else
  3057. return mmu_alloc_shadow_roots(vcpu);
  3058. }
  3059. void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
  3060. {
  3061. int i;
  3062. struct kvm_mmu_page *sp;
  3063. if (vcpu->arch.mmu->direct_map)
  3064. return;
  3065. if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
  3066. return;
  3067. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  3068. if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
  3069. hpa_t root = vcpu->arch.mmu->root_hpa;
  3070. sp = page_header(root);
  3071. /*
  3072. * Even if another CPU was marking the SP as unsync-ed
  3073. * simultaneously, any guest page table changes are not
  3074. * guaranteed to be visible anyway until this VCPU issues a TLB
  3075. * flush strictly after those changes are made. We only need to
  3076. * ensure that the other CPU sets these flags before any actual
  3077. * changes to the page tables are made. The comments in
  3078. * mmu_need_write_protect() describe what could go wrong if this
  3079. * requirement isn't satisfied.
  3080. */
  3081. if (!smp_load_acquire(&sp->unsync) &&
  3082. !smp_load_acquire(&sp->unsync_children))
  3083. return;
  3084. spin_lock(&vcpu->kvm->mmu_lock);
  3085. kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
  3086. mmu_sync_children(vcpu, sp);
  3087. kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
  3088. spin_unlock(&vcpu->kvm->mmu_lock);
  3089. return;
  3090. }
  3091. spin_lock(&vcpu->kvm->mmu_lock);
  3092. kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
  3093. for (i = 0; i < 4; ++i) {
  3094. hpa_t root = vcpu->arch.mmu->pae_root[i];
  3095. if (root && VALID_PAGE(root)) {
  3096. root &= PT64_BASE_ADDR_MASK;
  3097. sp = page_header(root);
  3098. mmu_sync_children(vcpu, sp);
  3099. }
  3100. }
  3101. kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
  3102. spin_unlock(&vcpu->kvm->mmu_lock);
  3103. }
  3104. EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
  3105. static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
  3106. u32 access, struct x86_exception *exception)
  3107. {
  3108. if (exception)
  3109. exception->error_code = 0;
  3110. return vaddr;
  3111. }
  3112. static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
  3113. u32 access,
  3114. struct x86_exception *exception)
  3115. {
  3116. if (exception)
  3117. exception->error_code = 0;
  3118. return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
  3119. }
  3120. static bool
  3121. __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
  3122. {
  3123. int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
  3124. return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
  3125. ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
  3126. }
  3127. static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
  3128. {
  3129. return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
  3130. }
  3131. static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
  3132. {
  3133. return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
  3134. }
  3135. static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3136. {
  3137. /*
  3138. * A nested guest cannot use the MMIO cache if it is using nested
  3139. * page tables, because cr2 is a nGPA while the cache stores GPAs.
  3140. */
  3141. if (mmu_is_nested(vcpu))
  3142. return false;
  3143. if (direct)
  3144. return vcpu_match_mmio_gpa(vcpu, addr);
  3145. return vcpu_match_mmio_gva(vcpu, addr);
  3146. }
  3147. /* return true if reserved bit is detected on spte. */
  3148. static bool
  3149. walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
  3150. {
  3151. struct kvm_shadow_walk_iterator iterator;
  3152. u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
  3153. int root, leaf;
  3154. bool reserved = false;
  3155. if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
  3156. goto exit;
  3157. walk_shadow_page_lockless_begin(vcpu);
  3158. for (shadow_walk_init(&iterator, vcpu, addr),
  3159. leaf = root = iterator.level;
  3160. shadow_walk_okay(&iterator);
  3161. __shadow_walk_next(&iterator, spte)) {
  3162. spte = mmu_spte_get_lockless(iterator.sptep);
  3163. sptes[leaf - 1] = spte;
  3164. leaf--;
  3165. if (!is_shadow_present_pte(spte))
  3166. break;
  3167. reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
  3168. iterator.level);
  3169. }
  3170. walk_shadow_page_lockless_end(vcpu);
  3171. if (reserved) {
  3172. pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
  3173. __func__, addr);
  3174. while (root > leaf) {
  3175. pr_err("------ spte 0x%llx level %d.\n",
  3176. sptes[root - 1], root);
  3177. root--;
  3178. }
  3179. }
  3180. exit:
  3181. *sptep = spte;
  3182. return reserved;
  3183. }
  3184. static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3185. {
  3186. u64 spte;
  3187. bool reserved;
  3188. if (mmio_info_in_cache(vcpu, addr, direct))
  3189. return RET_PF_EMULATE;
  3190. reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
  3191. if (WARN_ON(reserved))
  3192. return -EINVAL;
  3193. if (is_mmio_spte(spte)) {
  3194. gfn_t gfn = get_mmio_spte_gfn(spte);
  3195. unsigned access = get_mmio_spte_access(spte);
  3196. if (!check_mmio_spte(vcpu, spte))
  3197. return RET_PF_INVALID;
  3198. if (direct)
  3199. addr = 0;
  3200. trace_handle_mmio_page_fault(addr, gfn, access);
  3201. vcpu_cache_mmio_info(vcpu, addr, gfn, access);
  3202. return RET_PF_EMULATE;
  3203. }
  3204. /*
  3205. * If the page table is zapped by other cpus, let CPU fault again on
  3206. * the address.
  3207. */
  3208. return RET_PF_RETRY;
  3209. }
  3210. static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
  3211. u32 error_code, gfn_t gfn)
  3212. {
  3213. if (unlikely(error_code & PFERR_RSVD_MASK))
  3214. return false;
  3215. if (!(error_code & PFERR_PRESENT_MASK) ||
  3216. !(error_code & PFERR_WRITE_MASK))
  3217. return false;
  3218. /*
  3219. * guest is writing the page which is write tracked which can
  3220. * not be fixed by page fault handler.
  3221. */
  3222. if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
  3223. return true;
  3224. return false;
  3225. }
  3226. static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
  3227. {
  3228. struct kvm_shadow_walk_iterator iterator;
  3229. u64 spte;
  3230. if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
  3231. return;
  3232. walk_shadow_page_lockless_begin(vcpu);
  3233. for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
  3234. clear_sp_write_flooding_count(iterator.sptep);
  3235. if (!is_shadow_present_pte(spte))
  3236. break;
  3237. }
  3238. walk_shadow_page_lockless_end(vcpu);
  3239. }
  3240. static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
  3241. u32 error_code, bool prefault)
  3242. {
  3243. gfn_t gfn = gva >> PAGE_SHIFT;
  3244. int r;
  3245. pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
  3246. if (page_fault_handle_page_track(vcpu, error_code, gfn))
  3247. return RET_PF_EMULATE;
  3248. r = mmu_topup_memory_caches(vcpu);
  3249. if (r)
  3250. return r;
  3251. MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
  3252. return nonpaging_map(vcpu, gva & PAGE_MASK,
  3253. error_code, gfn, prefault);
  3254. }
  3255. static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
  3256. {
  3257. struct kvm_arch_async_pf arch;
  3258. arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
  3259. arch.gfn = gfn;
  3260. arch.direct_map = vcpu->arch.mmu->direct_map;
  3261. arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
  3262. return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
  3263. }
  3264. bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
  3265. {
  3266. if (unlikely(!lapic_in_kernel(vcpu) ||
  3267. kvm_event_needs_reinjection(vcpu) ||
  3268. vcpu->arch.exception.pending))
  3269. return false;
  3270. if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
  3271. return false;
  3272. return kvm_x86_ops->interrupt_allowed(vcpu);
  3273. }
  3274. static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
  3275. gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
  3276. {
  3277. struct kvm_memory_slot *slot;
  3278. bool async;
  3279. /*
  3280. * Don't expose private memslots to L2.
  3281. */
  3282. if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
  3283. *pfn = KVM_PFN_NOSLOT;
  3284. return false;
  3285. }
  3286. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  3287. async = false;
  3288. *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
  3289. if (!async)
  3290. return false; /* *pfn has correct page already */
  3291. if (!prefault && kvm_can_do_async_pf(vcpu)) {
  3292. trace_kvm_try_async_get_page(gva, gfn);
  3293. if (kvm_find_async_pf_gfn(vcpu, gfn)) {
  3294. trace_kvm_async_pf_doublefault(gva, gfn);
  3295. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  3296. return true;
  3297. } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
  3298. return true;
  3299. }
  3300. *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
  3301. return false;
  3302. }
  3303. int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
  3304. u64 fault_address, char *insn, int insn_len)
  3305. {
  3306. int r = 1;
  3307. vcpu->arch.l1tf_flush_l1d = true;
  3308. switch (vcpu->arch.apf.host_apf_reason) {
  3309. default:
  3310. trace_kvm_page_fault(fault_address, error_code);
  3311. if (kvm_event_needs_reinjection(vcpu))
  3312. kvm_mmu_unprotect_page_virt(vcpu, fault_address);
  3313. r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
  3314. insn_len);
  3315. break;
  3316. case KVM_PV_REASON_PAGE_NOT_PRESENT:
  3317. vcpu->arch.apf.host_apf_reason = 0;
  3318. local_irq_disable();
  3319. kvm_async_pf_task_wait(fault_address, 0);
  3320. local_irq_enable();
  3321. break;
  3322. case KVM_PV_REASON_PAGE_READY:
  3323. vcpu->arch.apf.host_apf_reason = 0;
  3324. local_irq_disable();
  3325. kvm_async_pf_task_wake(fault_address);
  3326. local_irq_enable();
  3327. break;
  3328. }
  3329. return r;
  3330. }
  3331. EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
  3332. static bool
  3333. check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
  3334. {
  3335. int page_num = KVM_PAGES_PER_HPAGE(level);
  3336. gfn &= ~(page_num - 1);
  3337. return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
  3338. }
  3339. static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
  3340. bool prefault)
  3341. {
  3342. kvm_pfn_t pfn;
  3343. int r;
  3344. int level;
  3345. bool force_pt_level;
  3346. gfn_t gfn = gpa >> PAGE_SHIFT;
  3347. unsigned long mmu_seq;
  3348. int write = error_code & PFERR_WRITE_MASK;
  3349. bool map_writable;
  3350. MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
  3351. if (page_fault_handle_page_track(vcpu, error_code, gfn))
  3352. return RET_PF_EMULATE;
  3353. r = mmu_topup_memory_caches(vcpu);
  3354. if (r)
  3355. return r;
  3356. force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
  3357. PT_DIRECTORY_LEVEL);
  3358. level = mapping_level(vcpu, gfn, &force_pt_level);
  3359. if (likely(!force_pt_level)) {
  3360. if (level > PT_DIRECTORY_LEVEL &&
  3361. !check_hugepage_cache_consistency(vcpu, gfn, level))
  3362. level = PT_DIRECTORY_LEVEL;
  3363. gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
  3364. }
  3365. if (fast_page_fault(vcpu, gpa, level, error_code))
  3366. return RET_PF_RETRY;
  3367. mmu_seq = vcpu->kvm->mmu_notifier_seq;
  3368. smp_rmb();
  3369. if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
  3370. return RET_PF_RETRY;
  3371. if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
  3372. return r;
  3373. spin_lock(&vcpu->kvm->mmu_lock);
  3374. if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
  3375. goto out_unlock;
  3376. if (make_mmu_pages_available(vcpu) < 0)
  3377. goto out_unlock;
  3378. if (likely(!force_pt_level))
  3379. transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
  3380. r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
  3381. spin_unlock(&vcpu->kvm->mmu_lock);
  3382. return r;
  3383. out_unlock:
  3384. spin_unlock(&vcpu->kvm->mmu_lock);
  3385. kvm_release_pfn_clean(pfn);
  3386. return RET_PF_RETRY;
  3387. }
  3388. static void nonpaging_init_context(struct kvm_vcpu *vcpu,
  3389. struct kvm_mmu *context)
  3390. {
  3391. context->page_fault = nonpaging_page_fault;
  3392. context->gva_to_gpa = nonpaging_gva_to_gpa;
  3393. context->sync_page = nonpaging_sync_page;
  3394. context->invlpg = nonpaging_invlpg;
  3395. context->update_pte = nonpaging_update_pte;
  3396. context->root_level = 0;
  3397. context->shadow_root_level = PT32E_ROOT_LEVEL;
  3398. context->direct_map = true;
  3399. context->nx = false;
  3400. }
  3401. /*
  3402. * Find out if a previously cached root matching the new CR3/role is available.
  3403. * The current root is also inserted into the cache.
  3404. * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
  3405. * returned.
  3406. * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
  3407. * false is returned. This root should now be freed by the caller.
  3408. */
  3409. static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
  3410. union kvm_mmu_page_role new_role)
  3411. {
  3412. uint i;
  3413. struct kvm_mmu_root_info root;
  3414. struct kvm_mmu *mmu = vcpu->arch.mmu;
  3415. root.cr3 = mmu->get_cr3(vcpu);
  3416. root.hpa = mmu->root_hpa;
  3417. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  3418. swap(root, mmu->prev_roots[i]);
  3419. if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
  3420. page_header(root.hpa) != NULL &&
  3421. new_role.word == page_header(root.hpa)->role.word)
  3422. break;
  3423. }
  3424. mmu->root_hpa = root.hpa;
  3425. return i < KVM_MMU_NUM_PREV_ROOTS;
  3426. }
  3427. static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
  3428. union kvm_mmu_page_role new_role,
  3429. bool skip_tlb_flush)
  3430. {
  3431. struct kvm_mmu *mmu = vcpu->arch.mmu;
  3432. /*
  3433. * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
  3434. * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
  3435. * later if necessary.
  3436. */
  3437. if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
  3438. mmu->root_level >= PT64_ROOT_4LEVEL) {
  3439. if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
  3440. return false;
  3441. if (cached_root_available(vcpu, new_cr3, new_role)) {
  3442. /*
  3443. * It is possible that the cached previous root page is
  3444. * obsolete because of a change in the MMU
  3445. * generation number. However, that is accompanied by
  3446. * KVM_REQ_MMU_RELOAD, which will free the root that we
  3447. * have set here and allocate a new one.
  3448. */
  3449. kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
  3450. if (!skip_tlb_flush) {
  3451. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  3452. kvm_x86_ops->tlb_flush(vcpu, true);
  3453. }
  3454. /*
  3455. * The last MMIO access's GVA and GPA are cached in the
  3456. * VCPU. When switching to a new CR3, that GVA->GPA
  3457. * mapping may no longer be valid. So clear any cached
  3458. * MMIO info even when we don't need to sync the shadow
  3459. * page tables.
  3460. */
  3461. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  3462. __clear_sp_write_flooding_count(
  3463. page_header(mmu->root_hpa));
  3464. return true;
  3465. }
  3466. }
  3467. return false;
  3468. }
  3469. static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
  3470. union kvm_mmu_page_role new_role,
  3471. bool skip_tlb_flush)
  3472. {
  3473. if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
  3474. kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
  3475. KVM_MMU_ROOT_CURRENT);
  3476. }
  3477. void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
  3478. {
  3479. __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
  3480. skip_tlb_flush);
  3481. }
  3482. EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
  3483. static unsigned long get_cr3(struct kvm_vcpu *vcpu)
  3484. {
  3485. return kvm_read_cr3(vcpu);
  3486. }
  3487. static void inject_page_fault(struct kvm_vcpu *vcpu,
  3488. struct x86_exception *fault)
  3489. {
  3490. vcpu->arch.mmu->inject_page_fault(vcpu, fault);
  3491. }
  3492. static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
  3493. unsigned access, int *nr_present)
  3494. {
  3495. if (unlikely(is_mmio_spte(*sptep))) {
  3496. if (gfn != get_mmio_spte_gfn(*sptep)) {
  3497. mmu_spte_clear_no_track(sptep);
  3498. return true;
  3499. }
  3500. (*nr_present)++;
  3501. mark_mmio_spte(vcpu, sptep, gfn, access);
  3502. return true;
  3503. }
  3504. return false;
  3505. }
  3506. static inline bool is_last_gpte(struct kvm_mmu *mmu,
  3507. unsigned level, unsigned gpte)
  3508. {
  3509. /*
  3510. * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
  3511. * If it is clear, there are no large pages at this level, so clear
  3512. * PT_PAGE_SIZE_MASK in gpte if that is the case.
  3513. */
  3514. gpte &= level - mmu->last_nonleaf_level;
  3515. /*
  3516. * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
  3517. * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
  3518. * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
  3519. */
  3520. gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
  3521. return gpte & PT_PAGE_SIZE_MASK;
  3522. }
  3523. #define PTTYPE_EPT 18 /* arbitrary */
  3524. #define PTTYPE PTTYPE_EPT
  3525. #include "paging_tmpl.h"
  3526. #undef PTTYPE
  3527. #define PTTYPE 64
  3528. #include "paging_tmpl.h"
  3529. #undef PTTYPE
  3530. #define PTTYPE 32
  3531. #include "paging_tmpl.h"
  3532. #undef PTTYPE
  3533. static void
  3534. __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
  3535. struct rsvd_bits_validate *rsvd_check,
  3536. int maxphyaddr, int level, bool nx, bool gbpages,
  3537. bool pse, bool amd)
  3538. {
  3539. u64 exb_bit_rsvd = 0;
  3540. u64 gbpages_bit_rsvd = 0;
  3541. u64 nonleaf_bit8_rsvd = 0;
  3542. rsvd_check->bad_mt_xwr = 0;
  3543. if (!nx)
  3544. exb_bit_rsvd = rsvd_bits(63, 63);
  3545. if (!gbpages)
  3546. gbpages_bit_rsvd = rsvd_bits(7, 7);
  3547. /*
  3548. * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
  3549. * leaf entries) on AMD CPUs only.
  3550. */
  3551. if (amd)
  3552. nonleaf_bit8_rsvd = rsvd_bits(8, 8);
  3553. switch (level) {
  3554. case PT32_ROOT_LEVEL:
  3555. /* no rsvd bits for 2 level 4K page table entries */
  3556. rsvd_check->rsvd_bits_mask[0][1] = 0;
  3557. rsvd_check->rsvd_bits_mask[0][0] = 0;
  3558. rsvd_check->rsvd_bits_mask[1][0] =
  3559. rsvd_check->rsvd_bits_mask[0][0];
  3560. if (!pse) {
  3561. rsvd_check->rsvd_bits_mask[1][1] = 0;
  3562. break;
  3563. }
  3564. if (is_cpuid_PSE36())
  3565. /* 36bits PSE 4MB page */
  3566. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
  3567. else
  3568. /* 32 bits PSE 4MB page */
  3569. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
  3570. break;
  3571. case PT32E_ROOT_LEVEL:
  3572. rsvd_check->rsvd_bits_mask[0][2] =
  3573. rsvd_bits(maxphyaddr, 63) |
  3574. rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
  3575. rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
  3576. rsvd_bits(maxphyaddr, 62); /* PDE */
  3577. rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
  3578. rsvd_bits(maxphyaddr, 62); /* PTE */
  3579. rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
  3580. rsvd_bits(maxphyaddr, 62) |
  3581. rsvd_bits(13, 20); /* large page */
  3582. rsvd_check->rsvd_bits_mask[1][0] =
  3583. rsvd_check->rsvd_bits_mask[0][0];
  3584. break;
  3585. case PT64_ROOT_5LEVEL:
  3586. rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
  3587. nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
  3588. rsvd_bits(maxphyaddr, 51);
  3589. rsvd_check->rsvd_bits_mask[1][4] =
  3590. rsvd_check->rsvd_bits_mask[0][4];
  3591. case PT64_ROOT_4LEVEL:
  3592. rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
  3593. nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
  3594. rsvd_bits(maxphyaddr, 51);
  3595. rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
  3596. nonleaf_bit8_rsvd | gbpages_bit_rsvd |
  3597. rsvd_bits(maxphyaddr, 51);
  3598. rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
  3599. rsvd_bits(maxphyaddr, 51);
  3600. rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
  3601. rsvd_bits(maxphyaddr, 51);
  3602. rsvd_check->rsvd_bits_mask[1][3] =
  3603. rsvd_check->rsvd_bits_mask[0][3];
  3604. rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
  3605. gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
  3606. rsvd_bits(13, 29);
  3607. rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
  3608. rsvd_bits(maxphyaddr, 51) |
  3609. rsvd_bits(13, 20); /* large page */
  3610. rsvd_check->rsvd_bits_mask[1][0] =
  3611. rsvd_check->rsvd_bits_mask[0][0];
  3612. break;
  3613. }
  3614. }
  3615. static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
  3616. struct kvm_mmu *context)
  3617. {
  3618. __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
  3619. cpuid_maxphyaddr(vcpu), context->root_level,
  3620. context->nx,
  3621. guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
  3622. is_pse(vcpu), guest_cpuid_is_amd(vcpu));
  3623. }
  3624. static void
  3625. __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
  3626. int maxphyaddr, bool execonly)
  3627. {
  3628. u64 bad_mt_xwr;
  3629. rsvd_check->rsvd_bits_mask[0][4] =
  3630. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
  3631. rsvd_check->rsvd_bits_mask[0][3] =
  3632. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
  3633. rsvd_check->rsvd_bits_mask[0][2] =
  3634. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
  3635. rsvd_check->rsvd_bits_mask[0][1] =
  3636. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
  3637. rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
  3638. /* large page */
  3639. rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
  3640. rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
  3641. rsvd_check->rsvd_bits_mask[1][2] =
  3642. rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
  3643. rsvd_check->rsvd_bits_mask[1][1] =
  3644. rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
  3645. rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
  3646. bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
  3647. bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
  3648. bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
  3649. bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
  3650. bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
  3651. if (!execonly) {
  3652. /* bits 0..2 must not be 100 unless VMX capabilities allow it */
  3653. bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
  3654. }
  3655. rsvd_check->bad_mt_xwr = bad_mt_xwr;
  3656. }
  3657. static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
  3658. struct kvm_mmu *context, bool execonly)
  3659. {
  3660. __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
  3661. cpuid_maxphyaddr(vcpu), execonly);
  3662. }
  3663. /*
  3664. * the page table on host is the shadow page table for the page
  3665. * table in guest or amd nested guest, its mmu features completely
  3666. * follow the features in guest.
  3667. */
  3668. void
  3669. reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
  3670. {
  3671. bool uses_nx = context->nx ||
  3672. context->mmu_role.base.smep_andnot_wp;
  3673. struct rsvd_bits_validate *shadow_zero_check;
  3674. int i;
  3675. /*
  3676. * Passing "true" to the last argument is okay; it adds a check
  3677. * on bit 8 of the SPTEs which KVM doesn't use anyway.
  3678. */
  3679. shadow_zero_check = &context->shadow_zero_check;
  3680. __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
  3681. boot_cpu_data.x86_phys_bits,
  3682. context->shadow_root_level, uses_nx,
  3683. guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
  3684. is_pse(vcpu), true);
  3685. if (!shadow_me_mask)
  3686. return;
  3687. for (i = context->shadow_root_level; --i >= 0;) {
  3688. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
  3689. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
  3690. }
  3691. }
  3692. EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
  3693. static inline bool boot_cpu_is_amd(void)
  3694. {
  3695. WARN_ON_ONCE(!tdp_enabled);
  3696. return shadow_x_mask == 0;
  3697. }
  3698. /*
  3699. * the direct page table on host, use as much mmu features as
  3700. * possible, however, kvm currently does not do execution-protection.
  3701. */
  3702. static void
  3703. reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
  3704. struct kvm_mmu *context)
  3705. {
  3706. struct rsvd_bits_validate *shadow_zero_check;
  3707. int i;
  3708. shadow_zero_check = &context->shadow_zero_check;
  3709. if (boot_cpu_is_amd())
  3710. __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
  3711. boot_cpu_data.x86_phys_bits,
  3712. context->shadow_root_level, false,
  3713. boot_cpu_has(X86_FEATURE_GBPAGES),
  3714. true, true);
  3715. else
  3716. __reset_rsvds_bits_mask_ept(shadow_zero_check,
  3717. boot_cpu_data.x86_phys_bits,
  3718. false);
  3719. if (!shadow_me_mask)
  3720. return;
  3721. for (i = context->shadow_root_level; --i >= 0;) {
  3722. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
  3723. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
  3724. }
  3725. }
  3726. /*
  3727. * as the comments in reset_shadow_zero_bits_mask() except it
  3728. * is the shadow page table for intel nested guest.
  3729. */
  3730. static void
  3731. reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
  3732. struct kvm_mmu *context, bool execonly)
  3733. {
  3734. __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
  3735. boot_cpu_data.x86_phys_bits, execonly);
  3736. }
  3737. #define BYTE_MASK(access) \
  3738. ((1 & (access) ? 2 : 0) | \
  3739. (2 & (access) ? 4 : 0) | \
  3740. (3 & (access) ? 8 : 0) | \
  3741. (4 & (access) ? 16 : 0) | \
  3742. (5 & (access) ? 32 : 0) | \
  3743. (6 & (access) ? 64 : 0) | \
  3744. (7 & (access) ? 128 : 0))
  3745. static void update_permission_bitmask(struct kvm_vcpu *vcpu,
  3746. struct kvm_mmu *mmu, bool ept)
  3747. {
  3748. unsigned byte;
  3749. const u8 x = BYTE_MASK(ACC_EXEC_MASK);
  3750. const u8 w = BYTE_MASK(ACC_WRITE_MASK);
  3751. const u8 u = BYTE_MASK(ACC_USER_MASK);
  3752. bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
  3753. bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
  3754. bool cr0_wp = is_write_protection(vcpu);
  3755. for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
  3756. unsigned pfec = byte << 1;
  3757. /*
  3758. * Each "*f" variable has a 1 bit for each UWX value
  3759. * that causes a fault with the given PFEC.
  3760. */
  3761. /* Faults from writes to non-writable pages */
  3762. u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
  3763. /* Faults from user mode accesses to supervisor pages */
  3764. u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
  3765. /* Faults from fetches of non-executable pages*/
  3766. u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
  3767. /* Faults from kernel mode fetches of user pages */
  3768. u8 smepf = 0;
  3769. /* Faults from kernel mode accesses of user pages */
  3770. u8 smapf = 0;
  3771. if (!ept) {
  3772. /* Faults from kernel mode accesses to user pages */
  3773. u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
  3774. /* Not really needed: !nx will cause pte.nx to fault */
  3775. if (!mmu->nx)
  3776. ff = 0;
  3777. /* Allow supervisor writes if !cr0.wp */
  3778. if (!cr0_wp)
  3779. wf = (pfec & PFERR_USER_MASK) ? wf : 0;
  3780. /* Disallow supervisor fetches of user code if cr4.smep */
  3781. if (cr4_smep)
  3782. smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
  3783. /*
  3784. * SMAP:kernel-mode data accesses from user-mode
  3785. * mappings should fault. A fault is considered
  3786. * as a SMAP violation if all of the following
  3787. * conditions are true:
  3788. * - X86_CR4_SMAP is set in CR4
  3789. * - A user page is accessed
  3790. * - The access is not a fetch
  3791. * - Page fault in kernel mode
  3792. * - if CPL = 3 or X86_EFLAGS_AC is clear
  3793. *
  3794. * Here, we cover the first three conditions.
  3795. * The fourth is computed dynamically in permission_fault();
  3796. * PFERR_RSVD_MASK bit will be set in PFEC if the access is
  3797. * *not* subject to SMAP restrictions.
  3798. */
  3799. if (cr4_smap)
  3800. smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
  3801. }
  3802. mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
  3803. }
  3804. }
  3805. /*
  3806. * PKU is an additional mechanism by which the paging controls access to
  3807. * user-mode addresses based on the value in the PKRU register. Protection
  3808. * key violations are reported through a bit in the page fault error code.
  3809. * Unlike other bits of the error code, the PK bit is not known at the
  3810. * call site of e.g. gva_to_gpa; it must be computed directly in
  3811. * permission_fault based on two bits of PKRU, on some machine state (CR4,
  3812. * CR0, EFER, CPL), and on other bits of the error code and the page tables.
  3813. *
  3814. * In particular the following conditions come from the error code, the
  3815. * page tables and the machine state:
  3816. * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
  3817. * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
  3818. * - PK is always zero if U=0 in the page tables
  3819. * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
  3820. *
  3821. * The PKRU bitmask caches the result of these four conditions. The error
  3822. * code (minus the P bit) and the page table's U bit form an index into the
  3823. * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
  3824. * with the two bits of the PKRU register corresponding to the protection key.
  3825. * For the first three conditions above the bits will be 00, thus masking
  3826. * away both AD and WD. For all reads or if the last condition holds, WD
  3827. * only will be masked away.
  3828. */
  3829. static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  3830. bool ept)
  3831. {
  3832. unsigned bit;
  3833. bool wp;
  3834. if (ept) {
  3835. mmu->pkru_mask = 0;
  3836. return;
  3837. }
  3838. /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
  3839. if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
  3840. mmu->pkru_mask = 0;
  3841. return;
  3842. }
  3843. wp = is_write_protection(vcpu);
  3844. for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
  3845. unsigned pfec, pkey_bits;
  3846. bool check_pkey, check_write, ff, uf, wf, pte_user;
  3847. pfec = bit << 1;
  3848. ff = pfec & PFERR_FETCH_MASK;
  3849. uf = pfec & PFERR_USER_MASK;
  3850. wf = pfec & PFERR_WRITE_MASK;
  3851. /* PFEC.RSVD is replaced by ACC_USER_MASK. */
  3852. pte_user = pfec & PFERR_RSVD_MASK;
  3853. /*
  3854. * Only need to check the access which is not an
  3855. * instruction fetch and is to a user page.
  3856. */
  3857. check_pkey = (!ff && pte_user);
  3858. /*
  3859. * write access is controlled by PKRU if it is a
  3860. * user access or CR0.WP = 1.
  3861. */
  3862. check_write = check_pkey && wf && (uf || wp);
  3863. /* PKRU.AD stops both read and write access. */
  3864. pkey_bits = !!check_pkey;
  3865. /* PKRU.WD stops write access. */
  3866. pkey_bits |= (!!check_write) << 1;
  3867. mmu->pkru_mask |= (pkey_bits & 3) << pfec;
  3868. }
  3869. }
  3870. static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
  3871. {
  3872. unsigned root_level = mmu->root_level;
  3873. mmu->last_nonleaf_level = root_level;
  3874. if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
  3875. mmu->last_nonleaf_level++;
  3876. }
  3877. static void paging64_init_context_common(struct kvm_vcpu *vcpu,
  3878. struct kvm_mmu *context,
  3879. int level)
  3880. {
  3881. context->nx = is_nx(vcpu);
  3882. context->root_level = level;
  3883. reset_rsvds_bits_mask(vcpu, context);
  3884. update_permission_bitmask(vcpu, context, false);
  3885. update_pkru_bitmask(vcpu, context, false);
  3886. update_last_nonleaf_level(vcpu, context);
  3887. MMU_WARN_ON(!is_pae(vcpu));
  3888. context->page_fault = paging64_page_fault;
  3889. context->gva_to_gpa = paging64_gva_to_gpa;
  3890. context->sync_page = paging64_sync_page;
  3891. context->invlpg = paging64_invlpg;
  3892. context->update_pte = paging64_update_pte;
  3893. context->shadow_root_level = level;
  3894. context->direct_map = false;
  3895. }
  3896. static void paging64_init_context(struct kvm_vcpu *vcpu,
  3897. struct kvm_mmu *context)
  3898. {
  3899. int root_level = is_la57_mode(vcpu) ?
  3900. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  3901. paging64_init_context_common(vcpu, context, root_level);
  3902. }
  3903. static void paging32_init_context(struct kvm_vcpu *vcpu,
  3904. struct kvm_mmu *context)
  3905. {
  3906. context->nx = false;
  3907. context->root_level = PT32_ROOT_LEVEL;
  3908. reset_rsvds_bits_mask(vcpu, context);
  3909. update_permission_bitmask(vcpu, context, false);
  3910. update_pkru_bitmask(vcpu, context, false);
  3911. update_last_nonleaf_level(vcpu, context);
  3912. context->page_fault = paging32_page_fault;
  3913. context->gva_to_gpa = paging32_gva_to_gpa;
  3914. context->sync_page = paging32_sync_page;
  3915. context->invlpg = paging32_invlpg;
  3916. context->update_pte = paging32_update_pte;
  3917. context->shadow_root_level = PT32E_ROOT_LEVEL;
  3918. context->direct_map = false;
  3919. }
  3920. static void paging32E_init_context(struct kvm_vcpu *vcpu,
  3921. struct kvm_mmu *context)
  3922. {
  3923. paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
  3924. }
  3925. static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
  3926. {
  3927. union kvm_mmu_extended_role ext = {0};
  3928. ext.cr0_pg = !!is_paging(vcpu);
  3929. ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
  3930. ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
  3931. ext.cr4_pse = !!is_pse(vcpu);
  3932. ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
  3933. ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
  3934. ext.valid = 1;
  3935. return ext;
  3936. }
  3937. static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
  3938. bool base_only)
  3939. {
  3940. union kvm_mmu_role role = {0};
  3941. role.base.access = ACC_ALL;
  3942. role.base.nxe = !!is_nx(vcpu);
  3943. role.base.cr4_pae = !!is_pae(vcpu);
  3944. role.base.cr0_wp = is_write_protection(vcpu);
  3945. role.base.smm = is_smm(vcpu);
  3946. role.base.guest_mode = is_guest_mode(vcpu);
  3947. if (base_only)
  3948. return role;
  3949. role.ext = kvm_calc_mmu_role_ext(vcpu);
  3950. return role;
  3951. }
  3952. static union kvm_mmu_role
  3953. kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
  3954. {
  3955. union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
  3956. role.base.ad_disabled = (shadow_accessed_mask == 0);
  3957. role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
  3958. role.base.direct = true;
  3959. return role;
  3960. }
  3961. static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
  3962. {
  3963. struct kvm_mmu *context = vcpu->arch.mmu;
  3964. union kvm_mmu_role new_role =
  3965. kvm_calc_tdp_mmu_root_page_role(vcpu, false);
  3966. new_role.base.word &= mmu_base_role_mask.word;
  3967. if (new_role.as_u64 == context->mmu_role.as_u64)
  3968. return;
  3969. context->mmu_role.as_u64 = new_role.as_u64;
  3970. context->page_fault = tdp_page_fault;
  3971. context->sync_page = nonpaging_sync_page;
  3972. context->invlpg = nonpaging_invlpg;
  3973. context->update_pte = nonpaging_update_pte;
  3974. context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
  3975. context->direct_map = true;
  3976. context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
  3977. context->get_cr3 = get_cr3;
  3978. context->get_pdptr = kvm_pdptr_read;
  3979. context->inject_page_fault = kvm_inject_page_fault;
  3980. if (!is_paging(vcpu)) {
  3981. context->nx = false;
  3982. context->gva_to_gpa = nonpaging_gva_to_gpa;
  3983. context->root_level = 0;
  3984. } else if (is_long_mode(vcpu)) {
  3985. context->nx = is_nx(vcpu);
  3986. context->root_level = is_la57_mode(vcpu) ?
  3987. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  3988. reset_rsvds_bits_mask(vcpu, context);
  3989. context->gva_to_gpa = paging64_gva_to_gpa;
  3990. } else if (is_pae(vcpu)) {
  3991. context->nx = is_nx(vcpu);
  3992. context->root_level = PT32E_ROOT_LEVEL;
  3993. reset_rsvds_bits_mask(vcpu, context);
  3994. context->gva_to_gpa = paging64_gva_to_gpa;
  3995. } else {
  3996. context->nx = false;
  3997. context->root_level = PT32_ROOT_LEVEL;
  3998. reset_rsvds_bits_mask(vcpu, context);
  3999. context->gva_to_gpa = paging32_gva_to_gpa;
  4000. }
  4001. update_permission_bitmask(vcpu, context, false);
  4002. update_pkru_bitmask(vcpu, context, false);
  4003. update_last_nonleaf_level(vcpu, context);
  4004. reset_tdp_shadow_zero_bits_mask(vcpu, context);
  4005. }
  4006. static union kvm_mmu_role
  4007. kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
  4008. {
  4009. union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
  4010. role.base.smep_andnot_wp = role.ext.cr4_smep &&
  4011. !is_write_protection(vcpu);
  4012. role.base.smap_andnot_wp = role.ext.cr4_smap &&
  4013. !is_write_protection(vcpu);
  4014. role.base.direct = !is_paging(vcpu);
  4015. if (!is_long_mode(vcpu))
  4016. role.base.level = PT32E_ROOT_LEVEL;
  4017. else if (is_la57_mode(vcpu))
  4018. role.base.level = PT64_ROOT_5LEVEL;
  4019. else
  4020. role.base.level = PT64_ROOT_4LEVEL;
  4021. return role;
  4022. }
  4023. void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
  4024. {
  4025. struct kvm_mmu *context = vcpu->arch.mmu;
  4026. union kvm_mmu_role new_role =
  4027. kvm_calc_shadow_mmu_root_page_role(vcpu, false);
  4028. new_role.base.word &= mmu_base_role_mask.word;
  4029. if (new_role.as_u64 == context->mmu_role.as_u64)
  4030. return;
  4031. if (!is_paging(vcpu))
  4032. nonpaging_init_context(vcpu, context);
  4033. else if (is_long_mode(vcpu))
  4034. paging64_init_context(vcpu, context);
  4035. else if (is_pae(vcpu))
  4036. paging32E_init_context(vcpu, context);
  4037. else
  4038. paging32_init_context(vcpu, context);
  4039. context->mmu_role.as_u64 = new_role.as_u64;
  4040. reset_shadow_zero_bits_mask(vcpu, context);
  4041. }
  4042. EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
  4043. static union kvm_mmu_role
  4044. kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
  4045. bool execonly)
  4046. {
  4047. union kvm_mmu_role role;
  4048. /* Base role is inherited from root_mmu */
  4049. role.base.word = vcpu->arch.root_mmu.mmu_role.base.word;
  4050. role.ext = kvm_calc_mmu_role_ext(vcpu);
  4051. role.base.level = PT64_ROOT_4LEVEL;
  4052. role.base.direct = false;
  4053. role.base.ad_disabled = !accessed_dirty;
  4054. role.base.guest_mode = true;
  4055. role.base.access = ACC_ALL;
  4056. role.ext.execonly = execonly;
  4057. return role;
  4058. }
  4059. void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
  4060. bool accessed_dirty, gpa_t new_eptp)
  4061. {
  4062. struct kvm_mmu *context = vcpu->arch.mmu;
  4063. union kvm_mmu_role new_role =
  4064. kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
  4065. execonly);
  4066. __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
  4067. new_role.base.word &= mmu_base_role_mask.word;
  4068. if (new_role.as_u64 == context->mmu_role.as_u64)
  4069. return;
  4070. context->shadow_root_level = PT64_ROOT_4LEVEL;
  4071. context->nx = true;
  4072. context->ept_ad = accessed_dirty;
  4073. context->page_fault = ept_page_fault;
  4074. context->gva_to_gpa = ept_gva_to_gpa;
  4075. context->sync_page = ept_sync_page;
  4076. context->invlpg = ept_invlpg;
  4077. context->update_pte = ept_update_pte;
  4078. context->root_level = PT64_ROOT_4LEVEL;
  4079. context->direct_map = false;
  4080. context->mmu_role.as_u64 = new_role.as_u64;
  4081. update_permission_bitmask(vcpu, context, true);
  4082. update_pkru_bitmask(vcpu, context, true);
  4083. update_last_nonleaf_level(vcpu, context);
  4084. reset_rsvds_bits_mask_ept(vcpu, context, execonly);
  4085. reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
  4086. }
  4087. EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
  4088. static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
  4089. {
  4090. struct kvm_mmu *context = vcpu->arch.mmu;
  4091. kvm_init_shadow_mmu(vcpu);
  4092. context->set_cr3 = kvm_x86_ops->set_cr3;
  4093. context->get_cr3 = get_cr3;
  4094. context->get_pdptr = kvm_pdptr_read;
  4095. context->inject_page_fault = kvm_inject_page_fault;
  4096. }
  4097. static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
  4098. {
  4099. union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
  4100. struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
  4101. new_role.base.word &= mmu_base_role_mask.word;
  4102. if (new_role.as_u64 == g_context->mmu_role.as_u64)
  4103. return;
  4104. g_context->mmu_role.as_u64 = new_role.as_u64;
  4105. g_context->get_cr3 = get_cr3;
  4106. g_context->get_pdptr = kvm_pdptr_read;
  4107. g_context->inject_page_fault = kvm_inject_page_fault;
  4108. /*
  4109. * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
  4110. * L1's nested page tables (e.g. EPT12). The nested translation
  4111. * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
  4112. * L2's page tables as the first level of translation and L1's
  4113. * nested page tables as the second level of translation. Basically
  4114. * the gva_to_gpa functions between mmu and nested_mmu are swapped.
  4115. */
  4116. if (!is_paging(vcpu)) {
  4117. g_context->nx = false;
  4118. g_context->root_level = 0;
  4119. g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
  4120. } else if (is_long_mode(vcpu)) {
  4121. g_context->nx = is_nx(vcpu);
  4122. g_context->root_level = is_la57_mode(vcpu) ?
  4123. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  4124. reset_rsvds_bits_mask(vcpu, g_context);
  4125. g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
  4126. } else if (is_pae(vcpu)) {
  4127. g_context->nx = is_nx(vcpu);
  4128. g_context->root_level = PT32E_ROOT_LEVEL;
  4129. reset_rsvds_bits_mask(vcpu, g_context);
  4130. g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
  4131. } else {
  4132. g_context->nx = false;
  4133. g_context->root_level = PT32_ROOT_LEVEL;
  4134. reset_rsvds_bits_mask(vcpu, g_context);
  4135. g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
  4136. }
  4137. update_permission_bitmask(vcpu, g_context, false);
  4138. update_pkru_bitmask(vcpu, g_context, false);
  4139. update_last_nonleaf_level(vcpu, g_context);
  4140. }
  4141. void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
  4142. {
  4143. if (reset_roots) {
  4144. uint i;
  4145. vcpu->arch.mmu->root_hpa = INVALID_PAGE;
  4146. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4147. vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
  4148. }
  4149. if (mmu_is_nested(vcpu))
  4150. init_kvm_nested_mmu(vcpu);
  4151. else if (tdp_enabled)
  4152. init_kvm_tdp_mmu(vcpu);
  4153. else
  4154. init_kvm_softmmu(vcpu);
  4155. }
  4156. EXPORT_SYMBOL_GPL(kvm_init_mmu);
  4157. static union kvm_mmu_page_role
  4158. kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
  4159. {
  4160. union kvm_mmu_role role;
  4161. if (tdp_enabled)
  4162. role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
  4163. else
  4164. role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
  4165. return role.base;
  4166. }
  4167. void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
  4168. {
  4169. kvm_mmu_unload(vcpu);
  4170. kvm_init_mmu(vcpu, true);
  4171. }
  4172. EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
  4173. int kvm_mmu_load(struct kvm_vcpu *vcpu)
  4174. {
  4175. int r;
  4176. r = mmu_topup_memory_caches(vcpu);
  4177. if (r)
  4178. goto out;
  4179. r = mmu_alloc_roots(vcpu);
  4180. kvm_mmu_sync_roots(vcpu);
  4181. if (r)
  4182. goto out;
  4183. kvm_mmu_load_cr3(vcpu);
  4184. kvm_x86_ops->tlb_flush(vcpu, true);
  4185. out:
  4186. return r;
  4187. }
  4188. EXPORT_SYMBOL_GPL(kvm_mmu_load);
  4189. void kvm_mmu_unload(struct kvm_vcpu *vcpu)
  4190. {
  4191. kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
  4192. WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
  4193. kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
  4194. WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
  4195. }
  4196. EXPORT_SYMBOL_GPL(kvm_mmu_unload);
  4197. static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
  4198. struct kvm_mmu_page *sp, u64 *spte,
  4199. const void *new)
  4200. {
  4201. if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
  4202. ++vcpu->kvm->stat.mmu_pde_zapped;
  4203. return;
  4204. }
  4205. ++vcpu->kvm->stat.mmu_pte_updated;
  4206. vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
  4207. }
  4208. static bool need_remote_flush(u64 old, u64 new)
  4209. {
  4210. if (!is_shadow_present_pte(old))
  4211. return false;
  4212. if (!is_shadow_present_pte(new))
  4213. return true;
  4214. if ((old ^ new) & PT64_BASE_ADDR_MASK)
  4215. return true;
  4216. old ^= shadow_nx_mask;
  4217. new ^= shadow_nx_mask;
  4218. return (old & ~new & PT64_PERM_MASK) != 0;
  4219. }
  4220. static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
  4221. const u8 *new, int *bytes)
  4222. {
  4223. u64 gentry;
  4224. int r;
  4225. /*
  4226. * Assume that the pte write on a page table of the same type
  4227. * as the current vcpu paging mode since we update the sptes only
  4228. * when they have the same mode.
  4229. */
  4230. if (is_pae(vcpu) && *bytes == 4) {
  4231. /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
  4232. *gpa &= ~(gpa_t)7;
  4233. *bytes = 8;
  4234. r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
  4235. if (r)
  4236. gentry = 0;
  4237. new = (const u8 *)&gentry;
  4238. }
  4239. switch (*bytes) {
  4240. case 4:
  4241. gentry = *(const u32 *)new;
  4242. break;
  4243. case 8:
  4244. gentry = *(const u64 *)new;
  4245. break;
  4246. default:
  4247. gentry = 0;
  4248. break;
  4249. }
  4250. return gentry;
  4251. }
  4252. /*
  4253. * If we're seeing too many writes to a page, it may no longer be a page table,
  4254. * or we may be forking, in which case it is better to unmap the page.
  4255. */
  4256. static bool detect_write_flooding(struct kvm_mmu_page *sp)
  4257. {
  4258. /*
  4259. * Skip write-flooding detected for the sp whose level is 1, because
  4260. * it can become unsync, then the guest page is not write-protected.
  4261. */
  4262. if (sp->role.level == PT_PAGE_TABLE_LEVEL)
  4263. return false;
  4264. atomic_inc(&sp->write_flooding_count);
  4265. return atomic_read(&sp->write_flooding_count) >= 3;
  4266. }
  4267. /*
  4268. * Misaligned accesses are too much trouble to fix up; also, they usually
  4269. * indicate a page is not used as a page table.
  4270. */
  4271. static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
  4272. int bytes)
  4273. {
  4274. unsigned offset, pte_size, misaligned;
  4275. pgprintk("misaligned: gpa %llx bytes %d role %x\n",
  4276. gpa, bytes, sp->role.word);
  4277. offset = offset_in_page(gpa);
  4278. pte_size = sp->role.cr4_pae ? 8 : 4;
  4279. /*
  4280. * Sometimes, the OS only writes the last one bytes to update status
  4281. * bits, for example, in linux, andb instruction is used in clear_bit().
  4282. */
  4283. if (!(offset & (pte_size - 1)) && bytes == 1)
  4284. return false;
  4285. misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
  4286. misaligned |= bytes < 4;
  4287. return misaligned;
  4288. }
  4289. static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
  4290. {
  4291. unsigned page_offset, quadrant;
  4292. u64 *spte;
  4293. int level;
  4294. page_offset = offset_in_page(gpa);
  4295. level = sp->role.level;
  4296. *nspte = 1;
  4297. if (!sp->role.cr4_pae) {
  4298. page_offset <<= 1; /* 32->64 */
  4299. /*
  4300. * A 32-bit pde maps 4MB while the shadow pdes map
  4301. * only 2MB. So we need to double the offset again
  4302. * and zap two pdes instead of one.
  4303. */
  4304. if (level == PT32_ROOT_LEVEL) {
  4305. page_offset &= ~7; /* kill rounding error */
  4306. page_offset <<= 1;
  4307. *nspte = 2;
  4308. }
  4309. quadrant = page_offset >> PAGE_SHIFT;
  4310. page_offset &= ~PAGE_MASK;
  4311. if (quadrant != sp->role.quadrant)
  4312. return NULL;
  4313. }
  4314. spte = &sp->spt[page_offset / sizeof(*spte)];
  4315. return spte;
  4316. }
  4317. static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
  4318. const u8 *new, int bytes,
  4319. struct kvm_page_track_notifier_node *node)
  4320. {
  4321. gfn_t gfn = gpa >> PAGE_SHIFT;
  4322. struct kvm_mmu_page *sp;
  4323. LIST_HEAD(invalid_list);
  4324. u64 entry, gentry, *spte;
  4325. int npte;
  4326. bool remote_flush, local_flush;
  4327. /*
  4328. * If we don't have indirect shadow pages, it means no page is
  4329. * write-protected, so we can exit simply.
  4330. */
  4331. if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
  4332. return;
  4333. remote_flush = local_flush = false;
  4334. pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
  4335. gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
  4336. /*
  4337. * No need to care whether allocation memory is successful
  4338. * or not since pte prefetch is skiped if it does not have
  4339. * enough objects in the cache.
  4340. */
  4341. mmu_topup_memory_caches(vcpu);
  4342. spin_lock(&vcpu->kvm->mmu_lock);
  4343. ++vcpu->kvm->stat.mmu_pte_write;
  4344. kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
  4345. for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
  4346. if (detect_write_misaligned(sp, gpa, bytes) ||
  4347. detect_write_flooding(sp)) {
  4348. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
  4349. ++vcpu->kvm->stat.mmu_flooded;
  4350. continue;
  4351. }
  4352. spte = get_written_sptes(sp, gpa, &npte);
  4353. if (!spte)
  4354. continue;
  4355. local_flush = true;
  4356. while (npte--) {
  4357. u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
  4358. entry = *spte;
  4359. mmu_page_zap_pte(vcpu->kvm, sp, spte);
  4360. if (gentry &&
  4361. !((sp->role.word ^ base_role)
  4362. & mmu_base_role_mask.word) && rmap_can_add(vcpu))
  4363. mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
  4364. if (need_remote_flush(entry, *spte))
  4365. remote_flush = true;
  4366. ++spte;
  4367. }
  4368. }
  4369. kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
  4370. kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
  4371. spin_unlock(&vcpu->kvm->mmu_lock);
  4372. }
  4373. int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
  4374. {
  4375. gpa_t gpa;
  4376. int r;
  4377. if (vcpu->arch.mmu->direct_map)
  4378. return 0;
  4379. gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
  4380. r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  4381. return r;
  4382. }
  4383. EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
  4384. static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
  4385. {
  4386. LIST_HEAD(invalid_list);
  4387. if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
  4388. return 0;
  4389. while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
  4390. if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
  4391. break;
  4392. ++vcpu->kvm->stat.mmu_recycled;
  4393. }
  4394. kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
  4395. if (!kvm_mmu_available_pages(vcpu->kvm))
  4396. return -ENOSPC;
  4397. return 0;
  4398. }
  4399. int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
  4400. void *insn, int insn_len)
  4401. {
  4402. int r, emulation_type = 0;
  4403. enum emulation_result er;
  4404. bool direct = vcpu->arch.mmu->direct_map;
  4405. /* With shadow page tables, fault_address contains a GVA or nGPA. */
  4406. if (vcpu->arch.mmu->direct_map) {
  4407. vcpu->arch.gpa_available = true;
  4408. vcpu->arch.gpa_val = cr2;
  4409. }
  4410. r = RET_PF_INVALID;
  4411. if (unlikely(error_code & PFERR_RSVD_MASK)) {
  4412. r = handle_mmio_page_fault(vcpu, cr2, direct);
  4413. if (r == RET_PF_EMULATE)
  4414. goto emulate;
  4415. }
  4416. if (r == RET_PF_INVALID) {
  4417. r = vcpu->arch.mmu->page_fault(vcpu, cr2,
  4418. lower_32_bits(error_code),
  4419. false);
  4420. WARN_ON(r == RET_PF_INVALID);
  4421. }
  4422. if (r == RET_PF_RETRY)
  4423. return 1;
  4424. if (r < 0)
  4425. return r;
  4426. /*
  4427. * Before emulating the instruction, check if the error code
  4428. * was due to a RO violation while translating the guest page.
  4429. * This can occur when using nested virtualization with nested
  4430. * paging in both guests. If true, we simply unprotect the page
  4431. * and resume the guest.
  4432. */
  4433. if (vcpu->arch.mmu->direct_map &&
  4434. (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
  4435. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
  4436. return 1;
  4437. }
  4438. /*
  4439. * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
  4440. * optimistically try to just unprotect the page and let the processor
  4441. * re-execute the instruction that caused the page fault. Do not allow
  4442. * retrying MMIO emulation, as it's not only pointless but could also
  4443. * cause us to enter an infinite loop because the processor will keep
  4444. * faulting on the non-existent MMIO address. Retrying an instruction
  4445. * from a nested guest is also pointless and dangerous as we are only
  4446. * explicitly shadowing L1's page tables, i.e. unprotecting something
  4447. * for L1 isn't going to magically fix whatever issue cause L2 to fail.
  4448. */
  4449. if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
  4450. emulation_type = EMULTYPE_ALLOW_RETRY;
  4451. emulate:
  4452. /*
  4453. * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
  4454. * This can happen if a guest gets a page-fault on data access but the HW
  4455. * table walker is not able to read the instruction page (e.g instruction
  4456. * page is not present in memory). In those cases we simply restart the
  4457. * guest.
  4458. */
  4459. if (unlikely(insn && !insn_len))
  4460. return 1;
  4461. er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
  4462. switch (er) {
  4463. case EMULATE_DONE:
  4464. return 1;
  4465. case EMULATE_USER_EXIT:
  4466. ++vcpu->stat.mmio_exits;
  4467. /* fall through */
  4468. case EMULATE_FAIL:
  4469. return 0;
  4470. default:
  4471. BUG();
  4472. }
  4473. }
  4474. EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
  4475. void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
  4476. {
  4477. struct kvm_mmu *mmu = vcpu->arch.mmu;
  4478. int i;
  4479. /* INVLPG on a * non-canonical address is a NOP according to the SDM. */
  4480. if (is_noncanonical_address(gva, vcpu))
  4481. return;
  4482. mmu->invlpg(vcpu, gva, mmu->root_hpa);
  4483. /*
  4484. * INVLPG is required to invalidate any global mappings for the VA,
  4485. * irrespective of PCID. Since it would take us roughly similar amount
  4486. * of work to determine whether any of the prev_root mappings of the VA
  4487. * is marked global, or to just sync it blindly, so we might as well
  4488. * just always sync it.
  4489. *
  4490. * Mappings not reachable via the current cr3 or the prev_roots will be
  4491. * synced when switching to that cr3, so nothing needs to be done here
  4492. * for them.
  4493. */
  4494. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4495. if (VALID_PAGE(mmu->prev_roots[i].hpa))
  4496. mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
  4497. kvm_x86_ops->tlb_flush_gva(vcpu, gva);
  4498. ++vcpu->stat.invlpg;
  4499. }
  4500. EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
  4501. void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
  4502. {
  4503. struct kvm_mmu *mmu = vcpu->arch.mmu;
  4504. bool tlb_flush = false;
  4505. uint i;
  4506. if (pcid == kvm_get_active_pcid(vcpu)) {
  4507. mmu->invlpg(vcpu, gva, mmu->root_hpa);
  4508. tlb_flush = true;
  4509. }
  4510. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  4511. if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
  4512. pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
  4513. mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
  4514. tlb_flush = true;
  4515. }
  4516. }
  4517. if (tlb_flush)
  4518. kvm_x86_ops->tlb_flush_gva(vcpu, gva);
  4519. ++vcpu->stat.invlpg;
  4520. /*
  4521. * Mappings not reachable via the current cr3 or the prev_roots will be
  4522. * synced when switching to that cr3, so nothing needs to be done here
  4523. * for them.
  4524. */
  4525. }
  4526. EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
  4527. void kvm_enable_tdp(void)
  4528. {
  4529. tdp_enabled = true;
  4530. }
  4531. EXPORT_SYMBOL_GPL(kvm_enable_tdp);
  4532. void kvm_disable_tdp(void)
  4533. {
  4534. tdp_enabled = false;
  4535. }
  4536. EXPORT_SYMBOL_GPL(kvm_disable_tdp);
  4537. static void free_mmu_pages(struct kvm_vcpu *vcpu)
  4538. {
  4539. free_page((unsigned long)vcpu->arch.mmu->pae_root);
  4540. free_page((unsigned long)vcpu->arch.mmu->lm_root);
  4541. }
  4542. static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
  4543. {
  4544. struct page *page;
  4545. int i;
  4546. if (tdp_enabled)
  4547. return 0;
  4548. /*
  4549. * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
  4550. * Therefore we need to allocate shadow page tables in the first
  4551. * 4GB of memory, which happens to fit the DMA32 zone.
  4552. */
  4553. page = alloc_page(GFP_KERNEL | __GFP_DMA32);
  4554. if (!page)
  4555. return -ENOMEM;
  4556. vcpu->arch.mmu->pae_root = page_address(page);
  4557. for (i = 0; i < 4; ++i)
  4558. vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
  4559. return 0;
  4560. }
  4561. int kvm_mmu_create(struct kvm_vcpu *vcpu)
  4562. {
  4563. uint i;
  4564. vcpu->arch.mmu = &vcpu->arch.root_mmu;
  4565. vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
  4566. vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
  4567. vcpu->arch.root_mmu.translate_gpa = translate_gpa;
  4568. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4569. vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
  4570. vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
  4571. vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
  4572. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4573. vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
  4574. vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
  4575. return alloc_mmu_pages(vcpu);
  4576. }
  4577. static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
  4578. struct kvm_memory_slot *slot,
  4579. struct kvm_page_track_notifier_node *node)
  4580. {
  4581. kvm_mmu_invalidate_zap_all_pages(kvm);
  4582. }
  4583. void kvm_mmu_init_vm(struct kvm *kvm)
  4584. {
  4585. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  4586. node->track_write = kvm_mmu_pte_write;
  4587. node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
  4588. kvm_page_track_register_notifier(kvm, node);
  4589. }
  4590. void kvm_mmu_uninit_vm(struct kvm *kvm)
  4591. {
  4592. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  4593. kvm_page_track_unregister_notifier(kvm, node);
  4594. }
  4595. /* The return value indicates if tlb flush on all vcpus is needed. */
  4596. typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
  4597. /* The caller should hold mmu-lock before calling this function. */
  4598. static __always_inline bool
  4599. slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4600. slot_level_handler fn, int start_level, int end_level,
  4601. gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
  4602. {
  4603. struct slot_rmap_walk_iterator iterator;
  4604. bool flush = false;
  4605. for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
  4606. end_gfn, &iterator) {
  4607. if (iterator.rmap)
  4608. flush |= fn(kvm, iterator.rmap);
  4609. if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
  4610. if (flush && lock_flush_tlb) {
  4611. kvm_flush_remote_tlbs(kvm);
  4612. flush = false;
  4613. }
  4614. cond_resched_lock(&kvm->mmu_lock);
  4615. }
  4616. }
  4617. if (flush && lock_flush_tlb) {
  4618. kvm_flush_remote_tlbs(kvm);
  4619. flush = false;
  4620. }
  4621. return flush;
  4622. }
  4623. static __always_inline bool
  4624. slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4625. slot_level_handler fn, int start_level, int end_level,
  4626. bool lock_flush_tlb)
  4627. {
  4628. return slot_handle_level_range(kvm, memslot, fn, start_level,
  4629. end_level, memslot->base_gfn,
  4630. memslot->base_gfn + memslot->npages - 1,
  4631. lock_flush_tlb);
  4632. }
  4633. static __always_inline bool
  4634. slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4635. slot_level_handler fn, bool lock_flush_tlb)
  4636. {
  4637. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
  4638. PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
  4639. }
  4640. static __always_inline bool
  4641. slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4642. slot_level_handler fn, bool lock_flush_tlb)
  4643. {
  4644. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
  4645. PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
  4646. }
  4647. static __always_inline bool
  4648. slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4649. slot_level_handler fn, bool lock_flush_tlb)
  4650. {
  4651. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
  4652. PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
  4653. }
  4654. void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
  4655. {
  4656. struct kvm_memslots *slots;
  4657. struct kvm_memory_slot *memslot;
  4658. int i;
  4659. spin_lock(&kvm->mmu_lock);
  4660. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  4661. slots = __kvm_memslots(kvm, i);
  4662. kvm_for_each_memslot(memslot, slots) {
  4663. gfn_t start, end;
  4664. start = max(gfn_start, memslot->base_gfn);
  4665. end = min(gfn_end, memslot->base_gfn + memslot->npages);
  4666. if (start >= end)
  4667. continue;
  4668. slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
  4669. PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
  4670. start, end - 1, true);
  4671. }
  4672. }
  4673. spin_unlock(&kvm->mmu_lock);
  4674. }
  4675. static bool slot_rmap_write_protect(struct kvm *kvm,
  4676. struct kvm_rmap_head *rmap_head)
  4677. {
  4678. return __rmap_write_protect(kvm, rmap_head, false);
  4679. }
  4680. void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
  4681. struct kvm_memory_slot *memslot)
  4682. {
  4683. bool flush;
  4684. spin_lock(&kvm->mmu_lock);
  4685. flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
  4686. false);
  4687. spin_unlock(&kvm->mmu_lock);
  4688. /*
  4689. * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
  4690. * which do tlb flush out of mmu-lock should be serialized by
  4691. * kvm->slots_lock otherwise tlb flush would be missed.
  4692. */
  4693. lockdep_assert_held(&kvm->slots_lock);
  4694. /*
  4695. * We can flush all the TLBs out of the mmu lock without TLB
  4696. * corruption since we just change the spte from writable to
  4697. * readonly so that we only need to care the case of changing
  4698. * spte from present to present (changing the spte from present
  4699. * to nonpresent will flush all the TLBs immediately), in other
  4700. * words, the only case we care is mmu_spte_update() where we
  4701. * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
  4702. * instead of PT_WRITABLE_MASK, that means it does not depend
  4703. * on PT_WRITABLE_MASK anymore.
  4704. */
  4705. if (flush)
  4706. kvm_flush_remote_tlbs(kvm);
  4707. }
  4708. static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
  4709. struct kvm_rmap_head *rmap_head)
  4710. {
  4711. u64 *sptep;
  4712. struct rmap_iterator iter;
  4713. int need_tlb_flush = 0;
  4714. kvm_pfn_t pfn;
  4715. struct kvm_mmu_page *sp;
  4716. restart:
  4717. for_each_rmap_spte(rmap_head, &iter, sptep) {
  4718. sp = page_header(__pa(sptep));
  4719. pfn = spte_to_pfn(*sptep);
  4720. /*
  4721. * We cannot do huge page mapping for indirect shadow pages,
  4722. * which are found on the last rmap (level = 1) when not using
  4723. * tdp; such shadow pages are synced with the page table in
  4724. * the guest, and the guest page table is using 4K page size
  4725. * mapping if the indirect sp has level = 1.
  4726. */
  4727. if (sp->role.direct &&
  4728. !kvm_is_reserved_pfn(pfn) &&
  4729. PageTransCompoundMap(pfn_to_page(pfn))) {
  4730. pte_list_remove(rmap_head, sptep);
  4731. need_tlb_flush = 1;
  4732. goto restart;
  4733. }
  4734. }
  4735. return need_tlb_flush;
  4736. }
  4737. void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
  4738. const struct kvm_memory_slot *memslot)
  4739. {
  4740. /* FIXME: const-ify all uses of struct kvm_memory_slot. */
  4741. spin_lock(&kvm->mmu_lock);
  4742. slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
  4743. kvm_mmu_zap_collapsible_spte, true);
  4744. spin_unlock(&kvm->mmu_lock);
  4745. }
  4746. void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
  4747. struct kvm_memory_slot *memslot)
  4748. {
  4749. bool flush;
  4750. spin_lock(&kvm->mmu_lock);
  4751. flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
  4752. spin_unlock(&kvm->mmu_lock);
  4753. lockdep_assert_held(&kvm->slots_lock);
  4754. /*
  4755. * It's also safe to flush TLBs out of mmu lock here as currently this
  4756. * function is only used for dirty logging, in which case flushing TLB
  4757. * out of mmu lock also guarantees no dirty pages will be lost in
  4758. * dirty_bitmap.
  4759. */
  4760. if (flush)
  4761. kvm_flush_remote_tlbs(kvm);
  4762. }
  4763. EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
  4764. void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
  4765. struct kvm_memory_slot *memslot)
  4766. {
  4767. bool flush;
  4768. spin_lock(&kvm->mmu_lock);
  4769. flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
  4770. false);
  4771. spin_unlock(&kvm->mmu_lock);
  4772. /* see kvm_mmu_slot_remove_write_access */
  4773. lockdep_assert_held(&kvm->slots_lock);
  4774. if (flush)
  4775. kvm_flush_remote_tlbs(kvm);
  4776. }
  4777. EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
  4778. void kvm_mmu_slot_set_dirty(struct kvm *kvm,
  4779. struct kvm_memory_slot *memslot)
  4780. {
  4781. bool flush;
  4782. spin_lock(&kvm->mmu_lock);
  4783. flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
  4784. spin_unlock(&kvm->mmu_lock);
  4785. lockdep_assert_held(&kvm->slots_lock);
  4786. /* see kvm_mmu_slot_leaf_clear_dirty */
  4787. if (flush)
  4788. kvm_flush_remote_tlbs(kvm);
  4789. }
  4790. EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
  4791. #define BATCH_ZAP_PAGES 10
  4792. static void kvm_zap_obsolete_pages(struct kvm *kvm)
  4793. {
  4794. struct kvm_mmu_page *sp, *node;
  4795. int batch = 0;
  4796. restart:
  4797. list_for_each_entry_safe_reverse(sp, node,
  4798. &kvm->arch.active_mmu_pages, link) {
  4799. int ret;
  4800. /*
  4801. * No obsolete page exists before new created page since
  4802. * active_mmu_pages is the FIFO list.
  4803. */
  4804. if (!is_obsolete_sp(kvm, sp))
  4805. break;
  4806. /*
  4807. * Since we are reversely walking the list and the invalid
  4808. * list will be moved to the head, skip the invalid page
  4809. * can help us to avoid the infinity list walking.
  4810. */
  4811. if (sp->role.invalid)
  4812. continue;
  4813. /*
  4814. * Need not flush tlb since we only zap the sp with invalid
  4815. * generation number.
  4816. */
  4817. if (batch >= BATCH_ZAP_PAGES &&
  4818. cond_resched_lock(&kvm->mmu_lock)) {
  4819. batch = 0;
  4820. goto restart;
  4821. }
  4822. ret = kvm_mmu_prepare_zap_page(kvm, sp,
  4823. &kvm->arch.zapped_obsolete_pages);
  4824. batch += ret;
  4825. if (ret)
  4826. goto restart;
  4827. }
  4828. /*
  4829. * Should flush tlb before free page tables since lockless-walking
  4830. * may use the pages.
  4831. */
  4832. kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
  4833. }
  4834. /*
  4835. * Fast invalidate all shadow pages and use lock-break technique
  4836. * to zap obsolete pages.
  4837. *
  4838. * It's required when memslot is being deleted or VM is being
  4839. * destroyed, in these cases, we should ensure that KVM MMU does
  4840. * not use any resource of the being-deleted slot or all slots
  4841. * after calling the function.
  4842. */
  4843. void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
  4844. {
  4845. spin_lock(&kvm->mmu_lock);
  4846. trace_kvm_mmu_invalidate_zap_all_pages(kvm);
  4847. kvm->arch.mmu_valid_gen++;
  4848. /*
  4849. * Notify all vcpus to reload its shadow page table
  4850. * and flush TLB. Then all vcpus will switch to new
  4851. * shadow page table with the new mmu_valid_gen.
  4852. *
  4853. * Note: we should do this under the protection of
  4854. * mmu-lock, otherwise, vcpu would purge shadow page
  4855. * but miss tlb flush.
  4856. */
  4857. kvm_reload_remote_mmus(kvm);
  4858. kvm_zap_obsolete_pages(kvm);
  4859. spin_unlock(&kvm->mmu_lock);
  4860. }
  4861. static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
  4862. {
  4863. return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
  4864. }
  4865. void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
  4866. {
  4867. /*
  4868. * The very rare case: if the generation-number is round,
  4869. * zap all shadow pages.
  4870. */
  4871. if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
  4872. kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
  4873. kvm_mmu_invalidate_zap_all_pages(kvm);
  4874. }
  4875. }
  4876. static unsigned long
  4877. mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  4878. {
  4879. struct kvm *kvm;
  4880. int nr_to_scan = sc->nr_to_scan;
  4881. unsigned long freed = 0;
  4882. spin_lock(&kvm_lock);
  4883. list_for_each_entry(kvm, &vm_list, vm_list) {
  4884. int idx;
  4885. LIST_HEAD(invalid_list);
  4886. /*
  4887. * Never scan more than sc->nr_to_scan VM instances.
  4888. * Will not hit this condition practically since we do not try
  4889. * to shrink more than one VM and it is very unlikely to see
  4890. * !n_used_mmu_pages so many times.
  4891. */
  4892. if (!nr_to_scan--)
  4893. break;
  4894. /*
  4895. * n_used_mmu_pages is accessed without holding kvm->mmu_lock
  4896. * here. We may skip a VM instance errorneosly, but we do not
  4897. * want to shrink a VM that only started to populate its MMU
  4898. * anyway.
  4899. */
  4900. if (!kvm->arch.n_used_mmu_pages &&
  4901. !kvm_has_zapped_obsolete_pages(kvm))
  4902. continue;
  4903. idx = srcu_read_lock(&kvm->srcu);
  4904. spin_lock(&kvm->mmu_lock);
  4905. if (kvm_has_zapped_obsolete_pages(kvm)) {
  4906. kvm_mmu_commit_zap_page(kvm,
  4907. &kvm->arch.zapped_obsolete_pages);
  4908. goto unlock;
  4909. }
  4910. if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
  4911. freed++;
  4912. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  4913. unlock:
  4914. spin_unlock(&kvm->mmu_lock);
  4915. srcu_read_unlock(&kvm->srcu, idx);
  4916. /*
  4917. * unfair on small ones
  4918. * per-vm shrinkers cry out
  4919. * sadness comes quickly
  4920. */
  4921. list_move_tail(&kvm->vm_list, &vm_list);
  4922. break;
  4923. }
  4924. spin_unlock(&kvm_lock);
  4925. return freed;
  4926. }
  4927. static unsigned long
  4928. mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  4929. {
  4930. return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
  4931. }
  4932. static struct shrinker mmu_shrinker = {
  4933. .count_objects = mmu_shrink_count,
  4934. .scan_objects = mmu_shrink_scan,
  4935. .seeks = DEFAULT_SEEKS * 10,
  4936. };
  4937. static void mmu_destroy_caches(void)
  4938. {
  4939. kmem_cache_destroy(pte_list_desc_cache);
  4940. kmem_cache_destroy(mmu_page_header_cache);
  4941. }
  4942. int kvm_mmu_module_init(void)
  4943. {
  4944. int ret = -ENOMEM;
  4945. /*
  4946. * MMU roles use union aliasing which is, generally speaking, an
  4947. * undefined behavior. However, we supposedly know how compilers behave
  4948. * and the current status quo is unlikely to change. Guardians below are
  4949. * supposed to let us know if the assumption becomes false.
  4950. */
  4951. BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
  4952. BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
  4953. BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
  4954. kvm_mmu_reset_all_pte_masks();
  4955. pte_list_desc_cache = kmem_cache_create("pte_list_desc",
  4956. sizeof(struct pte_list_desc),
  4957. 0, SLAB_ACCOUNT, NULL);
  4958. if (!pte_list_desc_cache)
  4959. goto out;
  4960. mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
  4961. sizeof(struct kvm_mmu_page),
  4962. 0, SLAB_ACCOUNT, NULL);
  4963. if (!mmu_page_header_cache)
  4964. goto out;
  4965. if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
  4966. goto out;
  4967. ret = register_shrinker(&mmu_shrinker);
  4968. if (ret)
  4969. goto out;
  4970. return 0;
  4971. out:
  4972. mmu_destroy_caches();
  4973. return ret;
  4974. }
  4975. /*
  4976. * Calculate mmu pages needed for kvm.
  4977. */
  4978. unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
  4979. {
  4980. unsigned int nr_mmu_pages;
  4981. unsigned int nr_pages = 0;
  4982. struct kvm_memslots *slots;
  4983. struct kvm_memory_slot *memslot;
  4984. int i;
  4985. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  4986. slots = __kvm_memslots(kvm, i);
  4987. kvm_for_each_memslot(memslot, slots)
  4988. nr_pages += memslot->npages;
  4989. }
  4990. nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
  4991. nr_mmu_pages = max(nr_mmu_pages,
  4992. (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
  4993. return nr_mmu_pages;
  4994. }
  4995. void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
  4996. {
  4997. kvm_mmu_unload(vcpu);
  4998. free_mmu_pages(vcpu);
  4999. mmu_free_memory_caches(vcpu);
  5000. }
  5001. void kvm_mmu_module_exit(void)
  5002. {
  5003. mmu_destroy_caches();
  5004. percpu_counter_destroy(&kvm_total_used_mmu_pages);
  5005. unregister_shrinker(&mmu_shrinker);
  5006. mmu_audit_disable();
  5007. }