mmu.c 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Kernel-based Virtual Machine driver for Linux
  4. *
  5. * This module enables machines with Intel VT-x extensions to run virtual
  6. * machines without emulation or binary translation.
  7. *
  8. * MMU support
  9. *
  10. * Copyright (C) 2006 Qumranet, Inc.
  11. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  12. *
  13. * Authors:
  14. * Yaniv Kamay <[email protected]>
  15. * Avi Kivity <[email protected]>
  16. */
  17. #include "irq.h"
  18. #include "ioapic.h"
  19. #include "mmu.h"
  20. #include "mmu_internal.h"
  21. #include "tdp_mmu.h"
  22. #include "x86.h"
  23. #include "kvm_cache_regs.h"
  24. #include "kvm_emulate.h"
  25. #include "cpuid.h"
  26. #include "spte.h"
  27. #include <linux/kvm_host.h>
  28. #include <linux/types.h>
  29. #include <linux/string.h>
  30. #include <linux/mm.h>
  31. #include <linux/highmem.h>
  32. #include <linux/moduleparam.h>
  33. #include <linux/export.h>
  34. #include <linux/swap.h>
  35. #include <linux/hugetlb.h>
  36. #include <linux/compiler.h>
  37. #include <linux/srcu.h>
  38. #include <linux/slab.h>
  39. #include <linux/sched/signal.h>
  40. #include <linux/uaccess.h>
  41. #include <linux/hash.h>
  42. #include <linux/kern_levels.h>
  43. #include <linux/kstrtox.h>
  44. #include <linux/kthread.h>
  45. #include <asm/page.h>
  46. #include <asm/memtype.h>
  47. #include <asm/cmpxchg.h>
  48. #include <asm/io.h>
  49. #include <asm/set_memory.h>
  50. #include <asm/vmx.h>
  51. #include <asm/kvm_page_track.h>
  52. #include "trace.h"
  53. extern bool itlb_multihit_kvm_mitigation;
  54. static bool nx_hugepage_mitigation_hard_disabled;
  55. int __read_mostly nx_huge_pages = -1;
  56. static uint __read_mostly nx_huge_pages_recovery_period_ms;
  57. #ifdef CONFIG_PREEMPT_RT
  58. /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
  59. static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
  60. #else
  61. static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
  62. #endif
  63. static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
  64. static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
  65. static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
  66. static const struct kernel_param_ops nx_huge_pages_ops = {
  67. .set = set_nx_huge_pages,
  68. .get = get_nx_huge_pages,
  69. };
  70. static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
  71. .set = set_nx_huge_pages_recovery_param,
  72. .get = param_get_uint,
  73. };
  74. module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
  75. __MODULE_PARM_TYPE(nx_huge_pages, "bool");
  76. module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
  77. &nx_huge_pages_recovery_ratio, 0644);
  78. __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
  79. module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
  80. &nx_huge_pages_recovery_period_ms, 0644);
  81. __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
  82. static bool __read_mostly force_flush_and_sync_on_reuse;
  83. module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
  84. /*
  85. * When setting this variable to true it enables Two-Dimensional-Paging
  86. * where the hardware walks 2 page tables:
  87. * 1. the guest-virtual to guest-physical
  88. * 2. while doing 1. it walks guest-physical to host-physical
  89. * If the hardware supports that we don't need to do shadow paging.
  90. */
  91. bool tdp_enabled = false;
  92. static int max_huge_page_level __read_mostly;
  93. static int tdp_root_level __read_mostly;
  94. static int max_tdp_level __read_mostly;
  95. #ifdef MMU_DEBUG
  96. bool dbg = 0;
  97. module_param(dbg, bool, 0644);
  98. #endif
  99. #define PTE_PREFETCH_NUM 8
  100. #include <trace/events/kvm.h>
  101. /* make pte_list_desc fit well in cache lines */
  102. #define PTE_LIST_EXT 14
  103. /*
  104. * Slight optimization of cacheline layout, by putting `more' and `spte_count'
  105. * at the start; then accessing it will only use one single cacheline for
  106. * either full (entries==PTE_LIST_EXT) case or entries<=6.
  107. */
  108. struct pte_list_desc {
  109. struct pte_list_desc *more;
  110. /*
  111. * Stores number of entries stored in the pte_list_desc. No need to be
  112. * u64 but just for easier alignment. When PTE_LIST_EXT, means full.
  113. */
  114. u64 spte_count;
  115. u64 *sptes[PTE_LIST_EXT];
  116. };
  117. struct kvm_shadow_walk_iterator {
  118. u64 addr;
  119. hpa_t shadow_addr;
  120. u64 *sptep;
  121. int level;
  122. unsigned index;
  123. };
  124. #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
  125. for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
  126. (_root), (_addr)); \
  127. shadow_walk_okay(&(_walker)); \
  128. shadow_walk_next(&(_walker)))
  129. #define for_each_shadow_entry(_vcpu, _addr, _walker) \
  130. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  131. shadow_walk_okay(&(_walker)); \
  132. shadow_walk_next(&(_walker)))
  133. #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
  134. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  135. shadow_walk_okay(&(_walker)) && \
  136. ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
  137. __shadow_walk_next(&(_walker), spte))
  138. static struct kmem_cache *pte_list_desc_cache;
  139. struct kmem_cache *mmu_page_header_cache;
  140. static struct percpu_counter kvm_total_used_mmu_pages;
  141. static void mmu_spte_set(u64 *sptep, u64 spte);
  142. struct kvm_mmu_role_regs {
  143. const unsigned long cr0;
  144. const unsigned long cr4;
  145. const u64 efer;
  146. };
  147. #define CREATE_TRACE_POINTS
  148. #include "mmutrace.h"
  149. /*
  150. * Yes, lot's of underscores. They're a hint that you probably shouldn't be
  151. * reading from the role_regs. Once the root_role is constructed, it becomes
  152. * the single source of truth for the MMU's state.
  153. */
  154. #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag) \
  155. static inline bool __maybe_unused \
  156. ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs) \
  157. { \
  158. return !!(regs->reg & flag); \
  159. }
  160. BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
  161. BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
  162. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
  163. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
  164. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
  165. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
  166. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
  167. BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
  168. BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
  169. BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
  170. /*
  171. * The MMU itself (with a valid role) is the single source of truth for the
  172. * MMU. Do not use the regs used to build the MMU/role, nor the vCPU. The
  173. * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
  174. * and the vCPU may be incorrect/irrelevant.
  175. */
  176. #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name) \
  177. static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu) \
  178. { \
  179. return !!(mmu->cpu_role. base_or_ext . reg##_##name); \
  180. }
  181. BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
  182. BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pse);
  183. BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smep);
  184. BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smap);
  185. BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pke);
  186. BUILD_MMU_ROLE_ACCESSOR(ext, cr4, la57);
  187. BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
  188. BUILD_MMU_ROLE_ACCESSOR(ext, efer, lma);
  189. static inline bool is_cr0_pg(struct kvm_mmu *mmu)
  190. {
  191. return mmu->cpu_role.base.level > 0;
  192. }
  193. static inline bool is_cr4_pae(struct kvm_mmu *mmu)
  194. {
  195. return !mmu->cpu_role.base.has_4_byte_gpte;
  196. }
  197. static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
  198. {
  199. struct kvm_mmu_role_regs regs = {
  200. .cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
  201. .cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
  202. .efer = vcpu->arch.efer,
  203. };
  204. return regs;
  205. }
  206. static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
  207. {
  208. return kvm_read_cr3(vcpu);
  209. }
  210. static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
  211. struct kvm_mmu *mmu)
  212. {
  213. if (IS_ENABLED(CONFIG_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
  214. return kvm_read_cr3(vcpu);
  215. return mmu->get_guest_pgd(vcpu);
  216. }
  217. static inline bool kvm_available_flush_tlb_with_range(void)
  218. {
  219. return kvm_x86_ops.tlb_remote_flush_with_range;
  220. }
  221. static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
  222. struct kvm_tlb_range *range)
  223. {
  224. int ret = -ENOTSUPP;
  225. if (range && kvm_x86_ops.tlb_remote_flush_with_range)
  226. ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
  227. if (ret)
  228. kvm_flush_remote_tlbs(kvm);
  229. }
  230. void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
  231. u64 start_gfn, u64 pages)
  232. {
  233. struct kvm_tlb_range range;
  234. range.start_gfn = start_gfn;
  235. range.pages = pages;
  236. kvm_flush_remote_tlbs_with_range(kvm, &range);
  237. }
  238. static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
  239. unsigned int access)
  240. {
  241. u64 spte = make_mmio_spte(vcpu, gfn, access);
  242. trace_mark_mmio_spte(sptep, gfn, spte);
  243. mmu_spte_set(sptep, spte);
  244. }
  245. static gfn_t get_mmio_spte_gfn(u64 spte)
  246. {
  247. u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
  248. gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
  249. & shadow_nonpresent_or_rsvd_mask;
  250. return gpa >> PAGE_SHIFT;
  251. }
  252. static unsigned get_mmio_spte_access(u64 spte)
  253. {
  254. return spte & shadow_mmio_access_mask;
  255. }
  256. static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
  257. {
  258. u64 kvm_gen, spte_gen, gen;
  259. gen = kvm_vcpu_memslots(vcpu)->generation;
  260. if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
  261. return false;
  262. kvm_gen = gen & MMIO_SPTE_GEN_MASK;
  263. spte_gen = get_mmio_spte_generation(spte);
  264. trace_check_mmio_spte(spte, kvm_gen, spte_gen);
  265. return likely(kvm_gen == spte_gen);
  266. }
  267. static int is_cpuid_PSE36(void)
  268. {
  269. return 1;
  270. }
  271. #ifdef CONFIG_X86_64
  272. static void __set_spte(u64 *sptep, u64 spte)
  273. {
  274. WRITE_ONCE(*sptep, spte);
  275. }
  276. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  277. {
  278. WRITE_ONCE(*sptep, spte);
  279. }
  280. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  281. {
  282. return xchg(sptep, spte);
  283. }
  284. static u64 __get_spte_lockless(u64 *sptep)
  285. {
  286. return READ_ONCE(*sptep);
  287. }
  288. #else
  289. union split_spte {
  290. struct {
  291. u32 spte_low;
  292. u32 spte_high;
  293. };
  294. u64 spte;
  295. };
  296. static void count_spte_clear(u64 *sptep, u64 spte)
  297. {
  298. struct kvm_mmu_page *sp = sptep_to_sp(sptep);
  299. if (is_shadow_present_pte(spte))
  300. return;
  301. /* Ensure the spte is completely set before we increase the count */
  302. smp_wmb();
  303. sp->clear_spte_count++;
  304. }
  305. static void __set_spte(u64 *sptep, u64 spte)
  306. {
  307. union split_spte *ssptep, sspte;
  308. ssptep = (union split_spte *)sptep;
  309. sspte = (union split_spte)spte;
  310. ssptep->spte_high = sspte.spte_high;
  311. /*
  312. * If we map the spte from nonpresent to present, We should store
  313. * the high bits firstly, then set present bit, so cpu can not
  314. * fetch this spte while we are setting the spte.
  315. */
  316. smp_wmb();
  317. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  318. }
  319. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  320. {
  321. union split_spte *ssptep, sspte;
  322. ssptep = (union split_spte *)sptep;
  323. sspte = (union split_spte)spte;
  324. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  325. /*
  326. * If we map the spte from present to nonpresent, we should clear
  327. * present bit firstly to avoid vcpu fetch the old high bits.
  328. */
  329. smp_wmb();
  330. ssptep->spte_high = sspte.spte_high;
  331. count_spte_clear(sptep, spte);
  332. }
  333. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  334. {
  335. union split_spte *ssptep, sspte, orig;
  336. ssptep = (union split_spte *)sptep;
  337. sspte = (union split_spte)spte;
  338. /* xchg acts as a barrier before the setting of the high bits */
  339. orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
  340. orig.spte_high = ssptep->spte_high;
  341. ssptep->spte_high = sspte.spte_high;
  342. count_spte_clear(sptep, spte);
  343. return orig.spte;
  344. }
  345. /*
  346. * The idea using the light way get the spte on x86_32 guest is from
  347. * gup_get_pte (mm/gup.c).
  348. *
  349. * An spte tlb flush may be pending, because kvm_set_pte_rmap
  350. * coalesces them and we are running out of the MMU lock. Therefore
  351. * we need to protect against in-progress updates of the spte.
  352. *
  353. * Reading the spte while an update is in progress may get the old value
  354. * for the high part of the spte. The race is fine for a present->non-present
  355. * change (because the high part of the spte is ignored for non-present spte),
  356. * but for a present->present change we must reread the spte.
  357. *
  358. * All such changes are done in two steps (present->non-present and
  359. * non-present->present), hence it is enough to count the number of
  360. * present->non-present updates: if it changed while reading the spte,
  361. * we might have hit the race. This is done using clear_spte_count.
  362. */
  363. static u64 __get_spte_lockless(u64 *sptep)
  364. {
  365. struct kvm_mmu_page *sp = sptep_to_sp(sptep);
  366. union split_spte spte, *orig = (union split_spte *)sptep;
  367. int count;
  368. retry:
  369. count = sp->clear_spte_count;
  370. smp_rmb();
  371. spte.spte_low = orig->spte_low;
  372. smp_rmb();
  373. spte.spte_high = orig->spte_high;
  374. smp_rmb();
  375. if (unlikely(spte.spte_low != orig->spte_low ||
  376. count != sp->clear_spte_count))
  377. goto retry;
  378. return spte.spte;
  379. }
  380. #endif
  381. /* Rules for using mmu_spte_set:
  382. * Set the sptep from nonpresent to present.
  383. * Note: the sptep being assigned *must* be either not present
  384. * or in a state where the hardware will not attempt to update
  385. * the spte.
  386. */
  387. static void mmu_spte_set(u64 *sptep, u64 new_spte)
  388. {
  389. WARN_ON(is_shadow_present_pte(*sptep));
  390. __set_spte(sptep, new_spte);
  391. }
  392. /*
  393. * Update the SPTE (excluding the PFN), but do not track changes in its
  394. * accessed/dirty status.
  395. */
  396. static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
  397. {
  398. u64 old_spte = *sptep;
  399. WARN_ON(!is_shadow_present_pte(new_spte));
  400. check_spte_writable_invariants(new_spte);
  401. if (!is_shadow_present_pte(old_spte)) {
  402. mmu_spte_set(sptep, new_spte);
  403. return old_spte;
  404. }
  405. if (!spte_has_volatile_bits(old_spte))
  406. __update_clear_spte_fast(sptep, new_spte);
  407. else
  408. old_spte = __update_clear_spte_slow(sptep, new_spte);
  409. WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
  410. return old_spte;
  411. }
  412. /* Rules for using mmu_spte_update:
  413. * Update the state bits, it means the mapped pfn is not changed.
  414. *
  415. * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
  416. * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
  417. * spte, even though the writable spte might be cached on a CPU's TLB.
  418. *
  419. * Returns true if the TLB needs to be flushed
  420. */
  421. static bool mmu_spte_update(u64 *sptep, u64 new_spte)
  422. {
  423. bool flush = false;
  424. u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
  425. if (!is_shadow_present_pte(old_spte))
  426. return false;
  427. /*
  428. * For the spte updated out of mmu-lock is safe, since
  429. * we always atomically update it, see the comments in
  430. * spte_has_volatile_bits().
  431. */
  432. if (is_mmu_writable_spte(old_spte) &&
  433. !is_writable_pte(new_spte))
  434. flush = true;
  435. /*
  436. * Flush TLB when accessed/dirty states are changed in the page tables,
  437. * to guarantee consistency between TLB and page tables.
  438. */
  439. if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
  440. flush = true;
  441. kvm_set_pfn_accessed(spte_to_pfn(old_spte));
  442. }
  443. if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
  444. flush = true;
  445. kvm_set_pfn_dirty(spte_to_pfn(old_spte));
  446. }
  447. return flush;
  448. }
  449. /*
  450. * Rules for using mmu_spte_clear_track_bits:
  451. * It sets the sptep from present to nonpresent, and track the
  452. * state bits, it is used to clear the last level sptep.
  453. * Returns the old PTE.
  454. */
  455. static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  456. {
  457. kvm_pfn_t pfn;
  458. u64 old_spte = *sptep;
  459. int level = sptep_to_sp(sptep)->role.level;
  460. struct page *page;
  461. if (!is_shadow_present_pte(old_spte) ||
  462. !spte_has_volatile_bits(old_spte))
  463. __update_clear_spte_fast(sptep, 0ull);
  464. else
  465. old_spte = __update_clear_spte_slow(sptep, 0ull);
  466. if (!is_shadow_present_pte(old_spte))
  467. return old_spte;
  468. kvm_update_page_stats(kvm, level, -1);
  469. pfn = spte_to_pfn(old_spte);
  470. /*
  471. * KVM doesn't hold a reference to any pages mapped into the guest, and
  472. * instead uses the mmu_notifier to ensure that KVM unmaps any pages
  473. * before they are reclaimed. Sanity check that, if the pfn is backed
  474. * by a refcounted page, the refcount is elevated.
  475. */
  476. page = kvm_pfn_to_refcounted_page(pfn);
  477. WARN_ON(page && !page_count(page));
  478. if (is_accessed_spte(old_spte))
  479. kvm_set_pfn_accessed(pfn);
  480. if (is_dirty_spte(old_spte))
  481. kvm_set_pfn_dirty(pfn);
  482. return old_spte;
  483. }
  484. /*
  485. * Rules for using mmu_spte_clear_no_track:
  486. * Directly clear spte without caring the state bits of sptep,
  487. * it is used to set the upper level spte.
  488. */
  489. static void mmu_spte_clear_no_track(u64 *sptep)
  490. {
  491. __update_clear_spte_fast(sptep, 0ull);
  492. }
  493. static u64 mmu_spte_get_lockless(u64 *sptep)
  494. {
  495. return __get_spte_lockless(sptep);
  496. }
  497. /* Returns the Accessed status of the PTE and resets it at the same time. */
  498. static bool mmu_spte_age(u64 *sptep)
  499. {
  500. u64 spte = mmu_spte_get_lockless(sptep);
  501. if (!is_accessed_spte(spte))
  502. return false;
  503. if (spte_ad_enabled(spte)) {
  504. clear_bit((ffs(shadow_accessed_mask) - 1),
  505. (unsigned long *)sptep);
  506. } else {
  507. /*
  508. * Capture the dirty status of the page, so that it doesn't get
  509. * lost when the SPTE is marked for access tracking.
  510. */
  511. if (is_writable_pte(spte))
  512. kvm_set_pfn_dirty(spte_to_pfn(spte));
  513. spte = mark_spte_for_access_track(spte);
  514. mmu_spte_update_no_track(sptep, spte);
  515. }
  516. return true;
  517. }
  518. static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
  519. {
  520. if (is_tdp_mmu(vcpu->arch.mmu)) {
  521. kvm_tdp_mmu_walk_lockless_begin();
  522. } else {
  523. /*
  524. * Prevent page table teardown by making any free-er wait during
  525. * kvm_flush_remote_tlbs() IPI to all active vcpus.
  526. */
  527. local_irq_disable();
  528. /*
  529. * Make sure a following spte read is not reordered ahead of the write
  530. * to vcpu->mode.
  531. */
  532. smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
  533. }
  534. }
  535. static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
  536. {
  537. if (is_tdp_mmu(vcpu->arch.mmu)) {
  538. kvm_tdp_mmu_walk_lockless_end();
  539. } else {
  540. /*
  541. * Make sure the write to vcpu->mode is not reordered in front of
  542. * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
  543. * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
  544. */
  545. smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
  546. local_irq_enable();
  547. }
  548. }
  549. static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
  550. {
  551. int r;
  552. /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
  553. r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
  554. 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
  555. if (r)
  556. return r;
  557. r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
  558. PT64_ROOT_MAX_LEVEL);
  559. if (r)
  560. return r;
  561. if (maybe_indirect) {
  562. r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
  563. PT64_ROOT_MAX_LEVEL);
  564. if (r)
  565. return r;
  566. }
  567. return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
  568. PT64_ROOT_MAX_LEVEL);
  569. }
  570. static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
  571. {
  572. kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
  573. kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
  574. kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
  575. kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
  576. }
  577. static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
  578. {
  579. kmem_cache_free(pte_list_desc_cache, pte_list_desc);
  580. }
  581. static bool sp_has_gptes(struct kvm_mmu_page *sp);
  582. static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
  583. {
  584. if (sp->role.passthrough)
  585. return sp->gfn;
  586. if (!sp->role.direct)
  587. return sp->shadowed_translation[index] >> PAGE_SHIFT;
  588. return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
  589. }
  590. /*
  591. * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
  592. * that the SPTE itself may have a more constrained access permissions that
  593. * what the guest enforces. For example, a guest may create an executable
  594. * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
  595. */
  596. static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
  597. {
  598. if (sp_has_gptes(sp))
  599. return sp->shadowed_translation[index] & ACC_ALL;
  600. /*
  601. * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
  602. * KVM is not shadowing any guest page tables, so the "guest access
  603. * permissions" are just ACC_ALL.
  604. *
  605. * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
  606. * is shadowing a guest huge page with small pages, the guest access
  607. * permissions being shadowed are the access permissions of the huge
  608. * page.
  609. *
  610. * In both cases, sp->role.access contains the correct access bits.
  611. */
  612. return sp->role.access;
  613. }
  614. static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
  615. gfn_t gfn, unsigned int access)
  616. {
  617. if (sp_has_gptes(sp)) {
  618. sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
  619. return;
  620. }
  621. WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
  622. "access mismatch under %s page %llx (expected %u, got %u)\n",
  623. sp->role.passthrough ? "passthrough" : "direct",
  624. sp->gfn, kvm_mmu_page_get_access(sp, index), access);
  625. WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
  626. "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
  627. sp->role.passthrough ? "passthrough" : "direct",
  628. sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
  629. }
  630. static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
  631. unsigned int access)
  632. {
  633. gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
  634. kvm_mmu_page_set_translation(sp, index, gfn, access);
  635. }
  636. /*
  637. * Return the pointer to the large page information for a given gfn,
  638. * handling slots that are not large page aligned.
  639. */
  640. static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
  641. const struct kvm_memory_slot *slot, int level)
  642. {
  643. unsigned long idx;
  644. idx = gfn_to_index(gfn, slot->base_gfn, level);
  645. return &slot->arch.lpage_info[level - 2][idx];
  646. }
  647. static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
  648. gfn_t gfn, int count)
  649. {
  650. struct kvm_lpage_info *linfo;
  651. int i;
  652. for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
  653. linfo = lpage_info_slot(gfn, slot, i);
  654. linfo->disallow_lpage += count;
  655. WARN_ON(linfo->disallow_lpage < 0);
  656. }
  657. }
  658. void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
  659. {
  660. update_gfn_disallow_lpage_count(slot, gfn, 1);
  661. }
  662. void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
  663. {
  664. update_gfn_disallow_lpage_count(slot, gfn, -1);
  665. }
  666. static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  667. {
  668. struct kvm_memslots *slots;
  669. struct kvm_memory_slot *slot;
  670. gfn_t gfn;
  671. kvm->arch.indirect_shadow_pages++;
  672. gfn = sp->gfn;
  673. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  674. slot = __gfn_to_memslot(slots, gfn);
  675. /* the non-leaf shadow pages are keeping readonly. */
  676. if (sp->role.level > PG_LEVEL_4K)
  677. return kvm_slot_page_track_add_page(kvm, slot, gfn,
  678. KVM_PAGE_TRACK_WRITE);
  679. kvm_mmu_gfn_disallow_lpage(slot, gfn);
  680. if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
  681. kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
  682. }
  683. void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  684. {
  685. if (sp->lpage_disallowed)
  686. return;
  687. ++kvm->stat.nx_lpage_splits;
  688. list_add_tail(&sp->lpage_disallowed_link,
  689. &kvm->arch.lpage_disallowed_mmu_pages);
  690. sp->lpage_disallowed = true;
  691. }
  692. static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  693. {
  694. struct kvm_memslots *slots;
  695. struct kvm_memory_slot *slot;
  696. gfn_t gfn;
  697. kvm->arch.indirect_shadow_pages--;
  698. gfn = sp->gfn;
  699. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  700. slot = __gfn_to_memslot(slots, gfn);
  701. if (sp->role.level > PG_LEVEL_4K)
  702. return kvm_slot_page_track_remove_page(kvm, slot, gfn,
  703. KVM_PAGE_TRACK_WRITE);
  704. kvm_mmu_gfn_allow_lpage(slot, gfn);
  705. }
  706. void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  707. {
  708. --kvm->stat.nx_lpage_splits;
  709. sp->lpage_disallowed = false;
  710. list_del(&sp->lpage_disallowed_link);
  711. }
  712. static struct kvm_memory_slot *
  713. gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
  714. bool no_dirty_log)
  715. {
  716. struct kvm_memory_slot *slot;
  717. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  718. if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
  719. return NULL;
  720. if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
  721. return NULL;
  722. return slot;
  723. }
  724. /*
  725. * About rmap_head encoding:
  726. *
  727. * If the bit zero of rmap_head->val is clear, then it points to the only spte
  728. * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
  729. * pte_list_desc containing more mappings.
  730. */
  731. /*
  732. * Returns the number of pointers in the rmap chain, not counting the new one.
  733. */
  734. static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
  735. struct kvm_rmap_head *rmap_head)
  736. {
  737. struct pte_list_desc *desc;
  738. int count = 0;
  739. if (!rmap_head->val) {
  740. rmap_printk("%p %llx 0->1\n", spte, *spte);
  741. rmap_head->val = (unsigned long)spte;
  742. } else if (!(rmap_head->val & 1)) {
  743. rmap_printk("%p %llx 1->many\n", spte, *spte);
  744. desc = kvm_mmu_memory_cache_alloc(cache);
  745. desc->sptes[0] = (u64 *)rmap_head->val;
  746. desc->sptes[1] = spte;
  747. desc->spte_count = 2;
  748. rmap_head->val = (unsigned long)desc | 1;
  749. ++count;
  750. } else {
  751. rmap_printk("%p %llx many->many\n", spte, *spte);
  752. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  753. while (desc->spte_count == PTE_LIST_EXT) {
  754. count += PTE_LIST_EXT;
  755. if (!desc->more) {
  756. desc->more = kvm_mmu_memory_cache_alloc(cache);
  757. desc = desc->more;
  758. desc->spte_count = 0;
  759. break;
  760. }
  761. desc = desc->more;
  762. }
  763. count += desc->spte_count;
  764. desc->sptes[desc->spte_count++] = spte;
  765. }
  766. return count;
  767. }
  768. static void
  769. pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
  770. struct pte_list_desc *desc, int i,
  771. struct pte_list_desc *prev_desc)
  772. {
  773. int j = desc->spte_count - 1;
  774. desc->sptes[i] = desc->sptes[j];
  775. desc->sptes[j] = NULL;
  776. desc->spte_count--;
  777. if (desc->spte_count)
  778. return;
  779. if (!prev_desc && !desc->more)
  780. rmap_head->val = 0;
  781. else
  782. if (prev_desc)
  783. prev_desc->more = desc->more;
  784. else
  785. rmap_head->val = (unsigned long)desc->more | 1;
  786. mmu_free_pte_list_desc(desc);
  787. }
  788. static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
  789. {
  790. struct pte_list_desc *desc;
  791. struct pte_list_desc *prev_desc;
  792. int i;
  793. if (!rmap_head->val) {
  794. pr_err("%s: %p 0->BUG\n", __func__, spte);
  795. BUG();
  796. } else if (!(rmap_head->val & 1)) {
  797. rmap_printk("%p 1->0\n", spte);
  798. if ((u64 *)rmap_head->val != spte) {
  799. pr_err("%s: %p 1->BUG\n", __func__, spte);
  800. BUG();
  801. }
  802. rmap_head->val = 0;
  803. } else {
  804. rmap_printk("%p many->many\n", spte);
  805. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  806. prev_desc = NULL;
  807. while (desc) {
  808. for (i = 0; i < desc->spte_count; ++i) {
  809. if (desc->sptes[i] == spte) {
  810. pte_list_desc_remove_entry(rmap_head,
  811. desc, i, prev_desc);
  812. return;
  813. }
  814. }
  815. prev_desc = desc;
  816. desc = desc->more;
  817. }
  818. pr_err("%s: %p many->many\n", __func__, spte);
  819. BUG();
  820. }
  821. }
  822. static void kvm_zap_one_rmap_spte(struct kvm *kvm,
  823. struct kvm_rmap_head *rmap_head, u64 *sptep)
  824. {
  825. mmu_spte_clear_track_bits(kvm, sptep);
  826. pte_list_remove(sptep, rmap_head);
  827. }
  828. /* Return true if at least one SPTE was zapped, false otherwise */
  829. static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
  830. struct kvm_rmap_head *rmap_head)
  831. {
  832. struct pte_list_desc *desc, *next;
  833. int i;
  834. if (!rmap_head->val)
  835. return false;
  836. if (!(rmap_head->val & 1)) {
  837. mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
  838. goto out;
  839. }
  840. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  841. for (; desc; desc = next) {
  842. for (i = 0; i < desc->spte_count; i++)
  843. mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
  844. next = desc->more;
  845. mmu_free_pte_list_desc(desc);
  846. }
  847. out:
  848. /* rmap_head is meaningless now, remember to reset it */
  849. rmap_head->val = 0;
  850. return true;
  851. }
  852. unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
  853. {
  854. struct pte_list_desc *desc;
  855. unsigned int count = 0;
  856. if (!rmap_head->val)
  857. return 0;
  858. else if (!(rmap_head->val & 1))
  859. return 1;
  860. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  861. while (desc) {
  862. count += desc->spte_count;
  863. desc = desc->more;
  864. }
  865. return count;
  866. }
  867. static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
  868. const struct kvm_memory_slot *slot)
  869. {
  870. unsigned long idx;
  871. idx = gfn_to_index(gfn, slot->base_gfn, level);
  872. return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
  873. }
  874. static bool rmap_can_add(struct kvm_vcpu *vcpu)
  875. {
  876. struct kvm_mmu_memory_cache *mc;
  877. mc = &vcpu->arch.mmu_pte_list_desc_cache;
  878. return kvm_mmu_memory_cache_nr_free_objects(mc);
  879. }
  880. static void rmap_remove(struct kvm *kvm, u64 *spte)
  881. {
  882. struct kvm_memslots *slots;
  883. struct kvm_memory_slot *slot;
  884. struct kvm_mmu_page *sp;
  885. gfn_t gfn;
  886. struct kvm_rmap_head *rmap_head;
  887. sp = sptep_to_sp(spte);
  888. gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
  889. /*
  890. * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
  891. * so we have to determine which memslots to use based on context
  892. * information in sp->role.
  893. */
  894. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  895. slot = __gfn_to_memslot(slots, gfn);
  896. rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
  897. pte_list_remove(spte, rmap_head);
  898. }
  899. /*
  900. * Used by the following functions to iterate through the sptes linked by a
  901. * rmap. All fields are private and not assumed to be used outside.
  902. */
  903. struct rmap_iterator {
  904. /* private fields */
  905. struct pte_list_desc *desc; /* holds the sptep if not NULL */
  906. int pos; /* index of the sptep */
  907. };
  908. /*
  909. * Iteration must be started by this function. This should also be used after
  910. * removing/dropping sptes from the rmap link because in such cases the
  911. * information in the iterator may not be valid.
  912. *
  913. * Returns sptep if found, NULL otherwise.
  914. */
  915. static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
  916. struct rmap_iterator *iter)
  917. {
  918. u64 *sptep;
  919. if (!rmap_head->val)
  920. return NULL;
  921. if (!(rmap_head->val & 1)) {
  922. iter->desc = NULL;
  923. sptep = (u64 *)rmap_head->val;
  924. goto out;
  925. }
  926. iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  927. iter->pos = 0;
  928. sptep = iter->desc->sptes[iter->pos];
  929. out:
  930. BUG_ON(!is_shadow_present_pte(*sptep));
  931. return sptep;
  932. }
  933. /*
  934. * Must be used with a valid iterator: e.g. after rmap_get_first().
  935. *
  936. * Returns sptep if found, NULL otherwise.
  937. */
  938. static u64 *rmap_get_next(struct rmap_iterator *iter)
  939. {
  940. u64 *sptep;
  941. if (iter->desc) {
  942. if (iter->pos < PTE_LIST_EXT - 1) {
  943. ++iter->pos;
  944. sptep = iter->desc->sptes[iter->pos];
  945. if (sptep)
  946. goto out;
  947. }
  948. iter->desc = iter->desc->more;
  949. if (iter->desc) {
  950. iter->pos = 0;
  951. /* desc->sptes[0] cannot be NULL */
  952. sptep = iter->desc->sptes[iter->pos];
  953. goto out;
  954. }
  955. }
  956. return NULL;
  957. out:
  958. BUG_ON(!is_shadow_present_pte(*sptep));
  959. return sptep;
  960. }
  961. #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
  962. for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
  963. _spte_; _spte_ = rmap_get_next(_iter_))
  964. static void drop_spte(struct kvm *kvm, u64 *sptep)
  965. {
  966. u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
  967. if (is_shadow_present_pte(old_spte))
  968. rmap_remove(kvm, sptep);
  969. }
  970. static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
  971. {
  972. struct kvm_mmu_page *sp;
  973. sp = sptep_to_sp(sptep);
  974. WARN_ON(sp->role.level == PG_LEVEL_4K);
  975. drop_spte(kvm, sptep);
  976. if (flush)
  977. kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
  978. KVM_PAGES_PER_HPAGE(sp->role.level));
  979. }
  980. /*
  981. * Write-protect on the specified @sptep, @pt_protect indicates whether
  982. * spte write-protection is caused by protecting shadow page table.
  983. *
  984. * Note: write protection is difference between dirty logging and spte
  985. * protection:
  986. * - for dirty logging, the spte can be set to writable at anytime if
  987. * its dirty bitmap is properly set.
  988. * - for spte protection, the spte can be writable only after unsync-ing
  989. * shadow page.
  990. *
  991. * Return true if tlb need be flushed.
  992. */
  993. static bool spte_write_protect(u64 *sptep, bool pt_protect)
  994. {
  995. u64 spte = *sptep;
  996. if (!is_writable_pte(spte) &&
  997. !(pt_protect && is_mmu_writable_spte(spte)))
  998. return false;
  999. rmap_printk("spte %p %llx\n", sptep, *sptep);
  1000. if (pt_protect)
  1001. spte &= ~shadow_mmu_writable_mask;
  1002. spte = spte & ~PT_WRITABLE_MASK;
  1003. return mmu_spte_update(sptep, spte);
  1004. }
  1005. static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
  1006. bool pt_protect)
  1007. {
  1008. u64 *sptep;
  1009. struct rmap_iterator iter;
  1010. bool flush = false;
  1011. for_each_rmap_spte(rmap_head, &iter, sptep)
  1012. flush |= spte_write_protect(sptep, pt_protect);
  1013. return flush;
  1014. }
  1015. static bool spte_clear_dirty(u64 *sptep)
  1016. {
  1017. u64 spte = *sptep;
  1018. rmap_printk("spte %p %llx\n", sptep, *sptep);
  1019. MMU_WARN_ON(!spte_ad_enabled(spte));
  1020. spte &= ~shadow_dirty_mask;
  1021. return mmu_spte_update(sptep, spte);
  1022. }
  1023. static bool spte_wrprot_for_clear_dirty(u64 *sptep)
  1024. {
  1025. bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
  1026. (unsigned long *)sptep);
  1027. if (was_writable && !spte_ad_enabled(*sptep))
  1028. kvm_set_pfn_dirty(spte_to_pfn(*sptep));
  1029. return was_writable;
  1030. }
  1031. /*
  1032. * Gets the GFN ready for another round of dirty logging by clearing the
  1033. * - D bit on ad-enabled SPTEs, and
  1034. * - W bit on ad-disabled SPTEs.
  1035. * Returns true iff any D or W bits were cleared.
  1036. */
  1037. static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1038. const struct kvm_memory_slot *slot)
  1039. {
  1040. u64 *sptep;
  1041. struct rmap_iterator iter;
  1042. bool flush = false;
  1043. for_each_rmap_spte(rmap_head, &iter, sptep)
  1044. if (spte_ad_need_write_protect(*sptep))
  1045. flush |= spte_wrprot_for_clear_dirty(sptep);
  1046. else
  1047. flush |= spte_clear_dirty(sptep);
  1048. return flush;
  1049. }
  1050. /**
  1051. * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
  1052. * @kvm: kvm instance
  1053. * @slot: slot to protect
  1054. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1055. * @mask: indicates which pages we should protect
  1056. *
  1057. * Used when we do not need to care about huge page mappings.
  1058. */
  1059. static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
  1060. struct kvm_memory_slot *slot,
  1061. gfn_t gfn_offset, unsigned long mask)
  1062. {
  1063. struct kvm_rmap_head *rmap_head;
  1064. if (is_tdp_mmu_enabled(kvm))
  1065. kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
  1066. slot->base_gfn + gfn_offset, mask, true);
  1067. if (!kvm_memslots_have_rmaps(kvm))
  1068. return;
  1069. while (mask) {
  1070. rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1071. PG_LEVEL_4K, slot);
  1072. rmap_write_protect(rmap_head, false);
  1073. /* clear the first set bit */
  1074. mask &= mask - 1;
  1075. }
  1076. }
  1077. /**
  1078. * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
  1079. * protect the page if the D-bit isn't supported.
  1080. * @kvm: kvm instance
  1081. * @slot: slot to clear D-bit
  1082. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1083. * @mask: indicates which pages we should clear D-bit
  1084. *
  1085. * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
  1086. */
  1087. static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
  1088. struct kvm_memory_slot *slot,
  1089. gfn_t gfn_offset, unsigned long mask)
  1090. {
  1091. struct kvm_rmap_head *rmap_head;
  1092. if (is_tdp_mmu_enabled(kvm))
  1093. kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
  1094. slot->base_gfn + gfn_offset, mask, false);
  1095. if (!kvm_memslots_have_rmaps(kvm))
  1096. return;
  1097. while (mask) {
  1098. rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1099. PG_LEVEL_4K, slot);
  1100. __rmap_clear_dirty(kvm, rmap_head, slot);
  1101. /* clear the first set bit */
  1102. mask &= mask - 1;
  1103. }
  1104. }
  1105. /**
  1106. * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
  1107. * PT level pages.
  1108. *
  1109. * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
  1110. * enable dirty logging for them.
  1111. *
  1112. * We need to care about huge page mappings: e.g. during dirty logging we may
  1113. * have such mappings.
  1114. */
  1115. void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
  1116. struct kvm_memory_slot *slot,
  1117. gfn_t gfn_offset, unsigned long mask)
  1118. {
  1119. /*
  1120. * Huge pages are NOT write protected when we start dirty logging in
  1121. * initially-all-set mode; must write protect them here so that they
  1122. * are split to 4K on the first write.
  1123. *
  1124. * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
  1125. * of memslot has no such restriction, so the range can cross two large
  1126. * pages.
  1127. */
  1128. if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
  1129. gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
  1130. gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
  1131. if (READ_ONCE(eager_page_split))
  1132. kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
  1133. kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
  1134. /* Cross two large pages? */
  1135. if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
  1136. ALIGN(end << PAGE_SHIFT, PMD_SIZE))
  1137. kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
  1138. PG_LEVEL_2M);
  1139. }
  1140. /* Now handle 4K PTEs. */
  1141. if (kvm_x86_ops.cpu_dirty_log_size)
  1142. kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
  1143. else
  1144. kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
  1145. }
  1146. int kvm_cpu_dirty_log_size(void)
  1147. {
  1148. return kvm_x86_ops.cpu_dirty_log_size;
  1149. }
  1150. bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
  1151. struct kvm_memory_slot *slot, u64 gfn,
  1152. int min_level)
  1153. {
  1154. struct kvm_rmap_head *rmap_head;
  1155. int i;
  1156. bool write_protected = false;
  1157. if (kvm_memslots_have_rmaps(kvm)) {
  1158. for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
  1159. rmap_head = gfn_to_rmap(gfn, i, slot);
  1160. write_protected |= rmap_write_protect(rmap_head, true);
  1161. }
  1162. }
  1163. if (is_tdp_mmu_enabled(kvm))
  1164. write_protected |=
  1165. kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
  1166. return write_protected;
  1167. }
  1168. static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
  1169. {
  1170. struct kvm_memory_slot *slot;
  1171. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1172. return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
  1173. }
  1174. static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1175. const struct kvm_memory_slot *slot)
  1176. {
  1177. return kvm_zap_all_rmap_sptes(kvm, rmap_head);
  1178. }
  1179. static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1180. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1181. pte_t unused)
  1182. {
  1183. return __kvm_zap_rmap(kvm, rmap_head, slot);
  1184. }
  1185. static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1186. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1187. pte_t pte)
  1188. {
  1189. u64 *sptep;
  1190. struct rmap_iterator iter;
  1191. bool need_flush = false;
  1192. u64 new_spte;
  1193. kvm_pfn_t new_pfn;
  1194. WARN_ON(pte_huge(pte));
  1195. new_pfn = pte_pfn(pte);
  1196. restart:
  1197. for_each_rmap_spte(rmap_head, &iter, sptep) {
  1198. rmap_printk("spte %p %llx gfn %llx (%d)\n",
  1199. sptep, *sptep, gfn, level);
  1200. need_flush = true;
  1201. if (pte_write(pte)) {
  1202. kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
  1203. goto restart;
  1204. } else {
  1205. new_spte = kvm_mmu_changed_pte_notifier_make_spte(
  1206. *sptep, new_pfn);
  1207. mmu_spte_clear_track_bits(kvm, sptep);
  1208. mmu_spte_set(sptep, new_spte);
  1209. }
  1210. }
  1211. if (need_flush && kvm_available_flush_tlb_with_range()) {
  1212. kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
  1213. return false;
  1214. }
  1215. return need_flush;
  1216. }
  1217. struct slot_rmap_walk_iterator {
  1218. /* input fields. */
  1219. const struct kvm_memory_slot *slot;
  1220. gfn_t start_gfn;
  1221. gfn_t end_gfn;
  1222. int start_level;
  1223. int end_level;
  1224. /* output fields. */
  1225. gfn_t gfn;
  1226. struct kvm_rmap_head *rmap;
  1227. int level;
  1228. /* private field. */
  1229. struct kvm_rmap_head *end_rmap;
  1230. };
  1231. static void
  1232. rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
  1233. {
  1234. iterator->level = level;
  1235. iterator->gfn = iterator->start_gfn;
  1236. iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
  1237. iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
  1238. }
  1239. static void
  1240. slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
  1241. const struct kvm_memory_slot *slot, int start_level,
  1242. int end_level, gfn_t start_gfn, gfn_t end_gfn)
  1243. {
  1244. iterator->slot = slot;
  1245. iterator->start_level = start_level;
  1246. iterator->end_level = end_level;
  1247. iterator->start_gfn = start_gfn;
  1248. iterator->end_gfn = end_gfn;
  1249. rmap_walk_init_level(iterator, iterator->start_level);
  1250. }
  1251. static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
  1252. {
  1253. return !!iterator->rmap;
  1254. }
  1255. static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
  1256. {
  1257. while (++iterator->rmap <= iterator->end_rmap) {
  1258. iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
  1259. if (iterator->rmap->val)
  1260. return;
  1261. }
  1262. if (++iterator->level > iterator->end_level) {
  1263. iterator->rmap = NULL;
  1264. return;
  1265. }
  1266. rmap_walk_init_level(iterator, iterator->level);
  1267. }
  1268. #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
  1269. _start_gfn, _end_gfn, _iter_) \
  1270. for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
  1271. _end_level_, _start_gfn, _end_gfn); \
  1272. slot_rmap_walk_okay(_iter_); \
  1273. slot_rmap_walk_next(_iter_))
  1274. typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1275. struct kvm_memory_slot *slot, gfn_t gfn,
  1276. int level, pte_t pte);
  1277. static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
  1278. struct kvm_gfn_range *range,
  1279. rmap_handler_t handler)
  1280. {
  1281. struct slot_rmap_walk_iterator iterator;
  1282. bool ret = false;
  1283. for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
  1284. range->start, range->end - 1, &iterator)
  1285. ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
  1286. iterator.level, range->pte);
  1287. return ret;
  1288. }
  1289. bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
  1290. {
  1291. bool flush = false;
  1292. if (kvm_memslots_have_rmaps(kvm))
  1293. flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
  1294. if (is_tdp_mmu_enabled(kvm))
  1295. flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
  1296. return flush;
  1297. }
  1298. bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
  1299. {
  1300. bool flush = false;
  1301. if (kvm_memslots_have_rmaps(kvm))
  1302. flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
  1303. if (is_tdp_mmu_enabled(kvm))
  1304. flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
  1305. return flush;
  1306. }
  1307. static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1308. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1309. pte_t unused)
  1310. {
  1311. u64 *sptep;
  1312. struct rmap_iterator iter;
  1313. int young = 0;
  1314. for_each_rmap_spte(rmap_head, &iter, sptep)
  1315. young |= mmu_spte_age(sptep);
  1316. return young;
  1317. }
  1318. static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1319. struct kvm_memory_slot *slot, gfn_t gfn,
  1320. int level, pte_t unused)
  1321. {
  1322. u64 *sptep;
  1323. struct rmap_iterator iter;
  1324. for_each_rmap_spte(rmap_head, &iter, sptep)
  1325. if (is_accessed_spte(*sptep))
  1326. return true;
  1327. return false;
  1328. }
  1329. #define RMAP_RECYCLE_THRESHOLD 1000
  1330. static void __rmap_add(struct kvm *kvm,
  1331. struct kvm_mmu_memory_cache *cache,
  1332. const struct kvm_memory_slot *slot,
  1333. u64 *spte, gfn_t gfn, unsigned int access)
  1334. {
  1335. struct kvm_mmu_page *sp;
  1336. struct kvm_rmap_head *rmap_head;
  1337. int rmap_count;
  1338. sp = sptep_to_sp(spte);
  1339. kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
  1340. kvm_update_page_stats(kvm, sp->role.level, 1);
  1341. rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
  1342. rmap_count = pte_list_add(cache, spte, rmap_head);
  1343. if (rmap_count > kvm->stat.max_mmu_rmap_size)
  1344. kvm->stat.max_mmu_rmap_size = rmap_count;
  1345. if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
  1346. kvm_zap_all_rmap_sptes(kvm, rmap_head);
  1347. kvm_flush_remote_tlbs_with_address(
  1348. kvm, sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
  1349. }
  1350. }
  1351. static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
  1352. u64 *spte, gfn_t gfn, unsigned int access)
  1353. {
  1354. struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
  1355. __rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
  1356. }
  1357. bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
  1358. {
  1359. bool young = false;
  1360. if (kvm_memslots_have_rmaps(kvm))
  1361. young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
  1362. if (is_tdp_mmu_enabled(kvm))
  1363. young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
  1364. return young;
  1365. }
  1366. bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
  1367. {
  1368. bool young = false;
  1369. if (kvm_memslots_have_rmaps(kvm))
  1370. young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
  1371. if (is_tdp_mmu_enabled(kvm))
  1372. young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
  1373. return young;
  1374. }
  1375. #ifdef MMU_DEBUG
  1376. static int is_empty_shadow_page(u64 *spt)
  1377. {
  1378. u64 *pos;
  1379. u64 *end;
  1380. for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
  1381. if (is_shadow_present_pte(*pos)) {
  1382. printk(KERN_ERR "%s: %p %llx\n", __func__,
  1383. pos, *pos);
  1384. return 0;
  1385. }
  1386. return 1;
  1387. }
  1388. #endif
  1389. /*
  1390. * This value is the sum of all of the kvm instances's
  1391. * kvm->arch.n_used_mmu_pages values. We need a global,
  1392. * aggregate version in order to make the slab shrinker
  1393. * faster
  1394. */
  1395. static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
  1396. {
  1397. kvm->arch.n_used_mmu_pages += nr;
  1398. percpu_counter_add(&kvm_total_used_mmu_pages, nr);
  1399. }
  1400. static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  1401. {
  1402. kvm_mod_used_mmu_pages(kvm, +1);
  1403. kvm_account_pgtable_pages((void *)sp->spt, +1);
  1404. }
  1405. static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  1406. {
  1407. kvm_mod_used_mmu_pages(kvm, -1);
  1408. kvm_account_pgtable_pages((void *)sp->spt, -1);
  1409. }
  1410. static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
  1411. {
  1412. MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
  1413. hlist_del(&sp->hash_link);
  1414. list_del(&sp->link);
  1415. free_page((unsigned long)sp->spt);
  1416. if (!sp->role.direct)
  1417. free_page((unsigned long)sp->shadowed_translation);
  1418. kmem_cache_free(mmu_page_header_cache, sp);
  1419. }
  1420. static unsigned kvm_page_table_hashfn(gfn_t gfn)
  1421. {
  1422. return hash_64(gfn, KVM_MMU_HASH_SHIFT);
  1423. }
  1424. static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
  1425. struct kvm_mmu_page *sp, u64 *parent_pte)
  1426. {
  1427. if (!parent_pte)
  1428. return;
  1429. pte_list_add(cache, parent_pte, &sp->parent_ptes);
  1430. }
  1431. static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
  1432. u64 *parent_pte)
  1433. {
  1434. pte_list_remove(parent_pte, &sp->parent_ptes);
  1435. }
  1436. static void drop_parent_pte(struct kvm_mmu_page *sp,
  1437. u64 *parent_pte)
  1438. {
  1439. mmu_page_remove_parent_pte(sp, parent_pte);
  1440. mmu_spte_clear_no_track(parent_pte);
  1441. }
  1442. static void mark_unsync(u64 *spte);
  1443. static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
  1444. {
  1445. u64 *sptep;
  1446. struct rmap_iterator iter;
  1447. for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
  1448. mark_unsync(sptep);
  1449. }
  1450. }
  1451. static void mark_unsync(u64 *spte)
  1452. {
  1453. struct kvm_mmu_page *sp;
  1454. sp = sptep_to_sp(spte);
  1455. if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
  1456. return;
  1457. if (sp->unsync_children++)
  1458. return;
  1459. kvm_mmu_mark_parents_unsync(sp);
  1460. }
  1461. static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
  1462. struct kvm_mmu_page *sp)
  1463. {
  1464. return -1;
  1465. }
  1466. #define KVM_PAGE_ARRAY_NR 16
  1467. struct kvm_mmu_pages {
  1468. struct mmu_page_and_offset {
  1469. struct kvm_mmu_page *sp;
  1470. unsigned int idx;
  1471. } page[KVM_PAGE_ARRAY_NR];
  1472. unsigned int nr;
  1473. };
  1474. static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
  1475. int idx)
  1476. {
  1477. int i;
  1478. if (sp->unsync)
  1479. for (i=0; i < pvec->nr; i++)
  1480. if (pvec->page[i].sp == sp)
  1481. return 0;
  1482. pvec->page[pvec->nr].sp = sp;
  1483. pvec->page[pvec->nr].idx = idx;
  1484. pvec->nr++;
  1485. return (pvec->nr == KVM_PAGE_ARRAY_NR);
  1486. }
  1487. static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
  1488. {
  1489. --sp->unsync_children;
  1490. WARN_ON((int)sp->unsync_children < 0);
  1491. __clear_bit(idx, sp->unsync_child_bitmap);
  1492. }
  1493. static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
  1494. struct kvm_mmu_pages *pvec)
  1495. {
  1496. int i, ret, nr_unsync_leaf = 0;
  1497. for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
  1498. struct kvm_mmu_page *child;
  1499. u64 ent = sp->spt[i];
  1500. if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
  1501. clear_unsync_child_bit(sp, i);
  1502. continue;
  1503. }
  1504. child = to_shadow_page(ent & SPTE_BASE_ADDR_MASK);
  1505. if (child->unsync_children) {
  1506. if (mmu_pages_add(pvec, child, i))
  1507. return -ENOSPC;
  1508. ret = __mmu_unsync_walk(child, pvec);
  1509. if (!ret) {
  1510. clear_unsync_child_bit(sp, i);
  1511. continue;
  1512. } else if (ret > 0) {
  1513. nr_unsync_leaf += ret;
  1514. } else
  1515. return ret;
  1516. } else if (child->unsync) {
  1517. nr_unsync_leaf++;
  1518. if (mmu_pages_add(pvec, child, i))
  1519. return -ENOSPC;
  1520. } else
  1521. clear_unsync_child_bit(sp, i);
  1522. }
  1523. return nr_unsync_leaf;
  1524. }
  1525. #define INVALID_INDEX (-1)
  1526. static int mmu_unsync_walk(struct kvm_mmu_page *sp,
  1527. struct kvm_mmu_pages *pvec)
  1528. {
  1529. pvec->nr = 0;
  1530. if (!sp->unsync_children)
  1531. return 0;
  1532. mmu_pages_add(pvec, sp, INVALID_INDEX);
  1533. return __mmu_unsync_walk(sp, pvec);
  1534. }
  1535. static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  1536. {
  1537. WARN_ON(!sp->unsync);
  1538. trace_kvm_mmu_sync_page(sp);
  1539. sp->unsync = 0;
  1540. --kvm->stat.mmu_unsync;
  1541. }
  1542. static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  1543. struct list_head *invalid_list);
  1544. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  1545. struct list_head *invalid_list);
  1546. static bool sp_has_gptes(struct kvm_mmu_page *sp)
  1547. {
  1548. if (sp->role.direct)
  1549. return false;
  1550. if (sp->role.passthrough)
  1551. return false;
  1552. return true;
  1553. }
  1554. #define for_each_valid_sp(_kvm, _sp, _list) \
  1555. hlist_for_each_entry(_sp, _list, hash_link) \
  1556. if (is_obsolete_sp((_kvm), (_sp))) { \
  1557. } else
  1558. #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn) \
  1559. for_each_valid_sp(_kvm, _sp, \
  1560. &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
  1561. if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
  1562. static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  1563. struct list_head *invalid_list)
  1564. {
  1565. int ret = vcpu->arch.mmu->sync_page(vcpu, sp);
  1566. if (ret < 0)
  1567. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
  1568. return ret;
  1569. }
  1570. static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
  1571. struct list_head *invalid_list,
  1572. bool remote_flush)
  1573. {
  1574. if (!remote_flush && list_empty(invalid_list))
  1575. return false;
  1576. if (!list_empty(invalid_list))
  1577. kvm_mmu_commit_zap_page(kvm, invalid_list);
  1578. else
  1579. kvm_flush_remote_tlbs(kvm);
  1580. return true;
  1581. }
  1582. static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  1583. {
  1584. if (sp->role.invalid)
  1585. return true;
  1586. /* TDP MMU pages due not use the MMU generation. */
  1587. return !sp->tdp_mmu_page &&
  1588. unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
  1589. }
  1590. struct mmu_page_path {
  1591. struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
  1592. unsigned int idx[PT64_ROOT_MAX_LEVEL];
  1593. };
  1594. #define for_each_sp(pvec, sp, parents, i) \
  1595. for (i = mmu_pages_first(&pvec, &parents); \
  1596. i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
  1597. i = mmu_pages_next(&pvec, &parents, i))
  1598. static int mmu_pages_next(struct kvm_mmu_pages *pvec,
  1599. struct mmu_page_path *parents,
  1600. int i)
  1601. {
  1602. int n;
  1603. for (n = i+1; n < pvec->nr; n++) {
  1604. struct kvm_mmu_page *sp = pvec->page[n].sp;
  1605. unsigned idx = pvec->page[n].idx;
  1606. int level = sp->role.level;
  1607. parents->idx[level-1] = idx;
  1608. if (level == PG_LEVEL_4K)
  1609. break;
  1610. parents->parent[level-2] = sp;
  1611. }
  1612. return n;
  1613. }
  1614. static int mmu_pages_first(struct kvm_mmu_pages *pvec,
  1615. struct mmu_page_path *parents)
  1616. {
  1617. struct kvm_mmu_page *sp;
  1618. int level;
  1619. if (pvec->nr == 0)
  1620. return 0;
  1621. WARN_ON(pvec->page[0].idx != INVALID_INDEX);
  1622. sp = pvec->page[0].sp;
  1623. level = sp->role.level;
  1624. WARN_ON(level == PG_LEVEL_4K);
  1625. parents->parent[level-2] = sp;
  1626. /* Also set up a sentinel. Further entries in pvec are all
  1627. * children of sp, so this element is never overwritten.
  1628. */
  1629. parents->parent[level-1] = NULL;
  1630. return mmu_pages_next(pvec, parents, 0);
  1631. }
  1632. static void mmu_pages_clear_parents(struct mmu_page_path *parents)
  1633. {
  1634. struct kvm_mmu_page *sp;
  1635. unsigned int level = 0;
  1636. do {
  1637. unsigned int idx = parents->idx[level];
  1638. sp = parents->parent[level];
  1639. if (!sp)
  1640. return;
  1641. WARN_ON(idx == INVALID_INDEX);
  1642. clear_unsync_child_bit(sp, idx);
  1643. level++;
  1644. } while (!sp->unsync_children);
  1645. }
  1646. static int mmu_sync_children(struct kvm_vcpu *vcpu,
  1647. struct kvm_mmu_page *parent, bool can_yield)
  1648. {
  1649. int i;
  1650. struct kvm_mmu_page *sp;
  1651. struct mmu_page_path parents;
  1652. struct kvm_mmu_pages pages;
  1653. LIST_HEAD(invalid_list);
  1654. bool flush = false;
  1655. while (mmu_unsync_walk(parent, &pages)) {
  1656. bool protected = false;
  1657. for_each_sp(pages, sp, parents, i)
  1658. protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
  1659. if (protected) {
  1660. kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
  1661. flush = false;
  1662. }
  1663. for_each_sp(pages, sp, parents, i) {
  1664. kvm_unlink_unsync_page(vcpu->kvm, sp);
  1665. flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
  1666. mmu_pages_clear_parents(&parents);
  1667. }
  1668. if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
  1669. kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
  1670. if (!can_yield) {
  1671. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  1672. return -EINTR;
  1673. }
  1674. cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
  1675. flush = false;
  1676. }
  1677. }
  1678. kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
  1679. return 0;
  1680. }
  1681. static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
  1682. {
  1683. atomic_set(&sp->write_flooding_count, 0);
  1684. }
  1685. static void clear_sp_write_flooding_count(u64 *spte)
  1686. {
  1687. __clear_sp_write_flooding_count(sptep_to_sp(spte));
  1688. }
  1689. /*
  1690. * The vCPU is required when finding indirect shadow pages; the shadow
  1691. * page may already exist and syncing it needs the vCPU pointer in
  1692. * order to read guest page tables. Direct shadow pages are never
  1693. * unsync, thus @vcpu can be NULL if @role.direct is true.
  1694. */
  1695. static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
  1696. struct kvm_vcpu *vcpu,
  1697. gfn_t gfn,
  1698. struct hlist_head *sp_list,
  1699. union kvm_mmu_page_role role)
  1700. {
  1701. struct kvm_mmu_page *sp;
  1702. int ret;
  1703. int collisions = 0;
  1704. LIST_HEAD(invalid_list);
  1705. for_each_valid_sp(kvm, sp, sp_list) {
  1706. if (sp->gfn != gfn) {
  1707. collisions++;
  1708. continue;
  1709. }
  1710. if (sp->role.word != role.word) {
  1711. /*
  1712. * If the guest is creating an upper-level page, zap
  1713. * unsync pages for the same gfn. While it's possible
  1714. * the guest is using recursive page tables, in all
  1715. * likelihood the guest has stopped using the unsync
  1716. * page and is installing a completely unrelated page.
  1717. * Unsync pages must not be left as is, because the new
  1718. * upper-level page will be write-protected.
  1719. */
  1720. if (role.level > PG_LEVEL_4K && sp->unsync)
  1721. kvm_mmu_prepare_zap_page(kvm, sp,
  1722. &invalid_list);
  1723. continue;
  1724. }
  1725. /* unsync and write-flooding only apply to indirect SPs. */
  1726. if (sp->role.direct)
  1727. goto out;
  1728. if (sp->unsync) {
  1729. if (KVM_BUG_ON(!vcpu, kvm))
  1730. break;
  1731. /*
  1732. * The page is good, but is stale. kvm_sync_page does
  1733. * get the latest guest state, but (unlike mmu_unsync_children)
  1734. * it doesn't write-protect the page or mark it synchronized!
  1735. * This way the validity of the mapping is ensured, but the
  1736. * overhead of write protection is not incurred until the
  1737. * guest invalidates the TLB mapping. This allows multiple
  1738. * SPs for a single gfn to be unsync.
  1739. *
  1740. * If the sync fails, the page is zapped. If so, break
  1741. * in order to rebuild it.
  1742. */
  1743. ret = kvm_sync_page(vcpu, sp, &invalid_list);
  1744. if (ret < 0)
  1745. break;
  1746. WARN_ON(!list_empty(&invalid_list));
  1747. if (ret > 0)
  1748. kvm_flush_remote_tlbs(kvm);
  1749. }
  1750. __clear_sp_write_flooding_count(sp);
  1751. goto out;
  1752. }
  1753. sp = NULL;
  1754. ++kvm->stat.mmu_cache_miss;
  1755. out:
  1756. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  1757. if (collisions > kvm->stat.max_mmu_page_hash_collisions)
  1758. kvm->stat.max_mmu_page_hash_collisions = collisions;
  1759. return sp;
  1760. }
  1761. /* Caches used when allocating a new shadow page. */
  1762. struct shadow_page_caches {
  1763. struct kvm_mmu_memory_cache *page_header_cache;
  1764. struct kvm_mmu_memory_cache *shadow_page_cache;
  1765. struct kvm_mmu_memory_cache *shadowed_info_cache;
  1766. };
  1767. static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
  1768. struct shadow_page_caches *caches,
  1769. gfn_t gfn,
  1770. struct hlist_head *sp_list,
  1771. union kvm_mmu_page_role role)
  1772. {
  1773. struct kvm_mmu_page *sp;
  1774. sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
  1775. sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
  1776. if (!role.direct)
  1777. sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
  1778. set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
  1779. /*
  1780. * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
  1781. * depends on valid pages being added to the head of the list. See
  1782. * comments in kvm_zap_obsolete_pages().
  1783. */
  1784. sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
  1785. list_add(&sp->link, &kvm->arch.active_mmu_pages);
  1786. kvm_account_mmu_page(kvm, sp);
  1787. sp->gfn = gfn;
  1788. sp->role = role;
  1789. hlist_add_head(&sp->hash_link, sp_list);
  1790. if (sp_has_gptes(sp))
  1791. account_shadowed(kvm, sp);
  1792. return sp;
  1793. }
  1794. /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
  1795. static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
  1796. struct kvm_vcpu *vcpu,
  1797. struct shadow_page_caches *caches,
  1798. gfn_t gfn,
  1799. union kvm_mmu_page_role role)
  1800. {
  1801. struct hlist_head *sp_list;
  1802. struct kvm_mmu_page *sp;
  1803. bool created = false;
  1804. sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
  1805. sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
  1806. if (!sp) {
  1807. created = true;
  1808. sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
  1809. }
  1810. trace_kvm_mmu_get_page(sp, created);
  1811. return sp;
  1812. }
  1813. static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
  1814. gfn_t gfn,
  1815. union kvm_mmu_page_role role)
  1816. {
  1817. struct shadow_page_caches caches = {
  1818. .page_header_cache = &vcpu->arch.mmu_page_header_cache,
  1819. .shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
  1820. .shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
  1821. };
  1822. return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
  1823. }
  1824. static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
  1825. unsigned int access)
  1826. {
  1827. struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
  1828. union kvm_mmu_page_role role;
  1829. role = parent_sp->role;
  1830. role.level--;
  1831. role.access = access;
  1832. role.direct = direct;
  1833. role.passthrough = 0;
  1834. /*
  1835. * If the guest has 4-byte PTEs then that means it's using 32-bit,
  1836. * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
  1837. * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
  1838. * shadow each guest page table with multiple shadow page tables, which
  1839. * requires extra bookkeeping in the role.
  1840. *
  1841. * Specifically, to shadow the guest's page directory (which covers a
  1842. * 4GiB address space), KVM uses 4 PAE page directories, each mapping
  1843. * 1GiB of the address space. @role.quadrant encodes which quarter of
  1844. * the address space each maps.
  1845. *
  1846. * To shadow the guest's page tables (which each map a 4MiB region), KVM
  1847. * uses 2 PAE page tables, each mapping a 2MiB region. For these,
  1848. * @role.quadrant encodes which half of the region they map.
  1849. *
  1850. * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
  1851. * consumes bits 29:21. To consume bits 31:30, KVM's uses 4 shadow
  1852. * PDPTEs; those 4 PAE page directories are pre-allocated and their
  1853. * quadrant is assigned in mmu_alloc_root(). A 4-byte PTE consumes
  1854. * bits 21:12, while an 8-byte PTE consumes bits 20:12. To consume
  1855. * bit 21 in the PTE (the child here), KVM propagates that bit to the
  1856. * quadrant, i.e. sets quadrant to '0' or '1'. The parent 8-byte PDE
  1857. * covers bit 21 (see above), thus the quadrant is calculated from the
  1858. * _least_ significant bit of the PDE index.
  1859. */
  1860. if (role.has_4_byte_gpte) {
  1861. WARN_ON_ONCE(role.level != PG_LEVEL_4K);
  1862. role.quadrant = spte_index(sptep) & 1;
  1863. }
  1864. return role;
  1865. }
  1866. static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
  1867. u64 *sptep, gfn_t gfn,
  1868. bool direct, unsigned int access)
  1869. {
  1870. union kvm_mmu_page_role role;
  1871. if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
  1872. return ERR_PTR(-EEXIST);
  1873. role = kvm_mmu_child_role(sptep, direct, access);
  1874. return kvm_mmu_get_shadow_page(vcpu, gfn, role);
  1875. }
  1876. static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
  1877. struct kvm_vcpu *vcpu, hpa_t root,
  1878. u64 addr)
  1879. {
  1880. iterator->addr = addr;
  1881. iterator->shadow_addr = root;
  1882. iterator->level = vcpu->arch.mmu->root_role.level;
  1883. if (iterator->level >= PT64_ROOT_4LEVEL &&
  1884. vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
  1885. !vcpu->arch.mmu->root_role.direct)
  1886. iterator->level = PT32E_ROOT_LEVEL;
  1887. if (iterator->level == PT32E_ROOT_LEVEL) {
  1888. /*
  1889. * prev_root is currently only used for 64-bit hosts. So only
  1890. * the active root_hpa is valid here.
  1891. */
  1892. BUG_ON(root != vcpu->arch.mmu->root.hpa);
  1893. iterator->shadow_addr
  1894. = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
  1895. iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
  1896. --iterator->level;
  1897. if (!iterator->shadow_addr)
  1898. iterator->level = 0;
  1899. }
  1900. }
  1901. static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
  1902. struct kvm_vcpu *vcpu, u64 addr)
  1903. {
  1904. shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
  1905. addr);
  1906. }
  1907. static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
  1908. {
  1909. if (iterator->level < PG_LEVEL_4K)
  1910. return false;
  1911. iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
  1912. iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
  1913. return true;
  1914. }
  1915. static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
  1916. u64 spte)
  1917. {
  1918. if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
  1919. iterator->level = 0;
  1920. return;
  1921. }
  1922. iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
  1923. --iterator->level;
  1924. }
  1925. static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
  1926. {
  1927. __shadow_walk_next(iterator, *iterator->sptep);
  1928. }
  1929. static void __link_shadow_page(struct kvm *kvm,
  1930. struct kvm_mmu_memory_cache *cache, u64 *sptep,
  1931. struct kvm_mmu_page *sp, bool flush)
  1932. {
  1933. u64 spte;
  1934. BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
  1935. /*
  1936. * If an SPTE is present already, it must be a leaf and therefore
  1937. * a large one. Drop it, and flush the TLB if needed, before
  1938. * installing sp.
  1939. */
  1940. if (is_shadow_present_pte(*sptep))
  1941. drop_large_spte(kvm, sptep, flush);
  1942. spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
  1943. mmu_spte_set(sptep, spte);
  1944. mmu_page_add_parent_pte(cache, sp, sptep);
  1945. if (sp->unsync_children || sp->unsync)
  1946. mark_unsync(sptep);
  1947. }
  1948. static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
  1949. struct kvm_mmu_page *sp)
  1950. {
  1951. __link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
  1952. }
  1953. static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
  1954. unsigned direct_access)
  1955. {
  1956. if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
  1957. struct kvm_mmu_page *child;
  1958. /*
  1959. * For the direct sp, if the guest pte's dirty bit
  1960. * changed form clean to dirty, it will corrupt the
  1961. * sp's access: allow writable in the read-only sp,
  1962. * so we should update the spte at this point to get
  1963. * a new sp with the correct access.
  1964. */
  1965. child = to_shadow_page(*sptep & SPTE_BASE_ADDR_MASK);
  1966. if (child->role.access == direct_access)
  1967. return;
  1968. drop_parent_pte(child, sptep);
  1969. kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
  1970. }
  1971. }
  1972. /* Returns the number of zapped non-leaf child shadow pages. */
  1973. static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
  1974. u64 *spte, struct list_head *invalid_list)
  1975. {
  1976. u64 pte;
  1977. struct kvm_mmu_page *child;
  1978. pte = *spte;
  1979. if (is_shadow_present_pte(pte)) {
  1980. if (is_last_spte(pte, sp->role.level)) {
  1981. drop_spte(kvm, spte);
  1982. } else {
  1983. child = to_shadow_page(pte & SPTE_BASE_ADDR_MASK);
  1984. drop_parent_pte(child, spte);
  1985. /*
  1986. * Recursively zap nested TDP SPs, parentless SPs are
  1987. * unlikely to be used again in the near future. This
  1988. * avoids retaining a large number of stale nested SPs.
  1989. */
  1990. if (tdp_enabled && invalid_list &&
  1991. child->role.guest_mode && !child->parent_ptes.val)
  1992. return kvm_mmu_prepare_zap_page(kvm, child,
  1993. invalid_list);
  1994. }
  1995. } else if (is_mmio_spte(pte)) {
  1996. mmu_spte_clear_no_track(spte);
  1997. }
  1998. return 0;
  1999. }
  2000. static int kvm_mmu_page_unlink_children(struct kvm *kvm,
  2001. struct kvm_mmu_page *sp,
  2002. struct list_head *invalid_list)
  2003. {
  2004. int zapped = 0;
  2005. unsigned i;
  2006. for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
  2007. zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
  2008. return zapped;
  2009. }
  2010. static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
  2011. {
  2012. u64 *sptep;
  2013. struct rmap_iterator iter;
  2014. while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
  2015. drop_parent_pte(sp, sptep);
  2016. }
  2017. static int mmu_zap_unsync_children(struct kvm *kvm,
  2018. struct kvm_mmu_page *parent,
  2019. struct list_head *invalid_list)
  2020. {
  2021. int i, zapped = 0;
  2022. struct mmu_page_path parents;
  2023. struct kvm_mmu_pages pages;
  2024. if (parent->role.level == PG_LEVEL_4K)
  2025. return 0;
  2026. while (mmu_unsync_walk(parent, &pages)) {
  2027. struct kvm_mmu_page *sp;
  2028. for_each_sp(pages, sp, parents, i) {
  2029. kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2030. mmu_pages_clear_parents(&parents);
  2031. zapped++;
  2032. }
  2033. }
  2034. return zapped;
  2035. }
  2036. static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
  2037. struct kvm_mmu_page *sp,
  2038. struct list_head *invalid_list,
  2039. int *nr_zapped)
  2040. {
  2041. bool list_unstable, zapped_root = false;
  2042. lockdep_assert_held_write(&kvm->mmu_lock);
  2043. trace_kvm_mmu_prepare_zap_page(sp);
  2044. ++kvm->stat.mmu_shadow_zapped;
  2045. *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
  2046. *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
  2047. kvm_mmu_unlink_parents(sp);
  2048. /* Zapping children means active_mmu_pages has become unstable. */
  2049. list_unstable = *nr_zapped;
  2050. if (!sp->role.invalid && sp_has_gptes(sp))
  2051. unaccount_shadowed(kvm, sp);
  2052. if (sp->unsync)
  2053. kvm_unlink_unsync_page(kvm, sp);
  2054. if (!sp->root_count) {
  2055. /* Count self */
  2056. (*nr_zapped)++;
  2057. /*
  2058. * Already invalid pages (previously active roots) are not on
  2059. * the active page list. See list_del() in the "else" case of
  2060. * !sp->root_count.
  2061. */
  2062. if (sp->role.invalid)
  2063. list_add(&sp->link, invalid_list);
  2064. else
  2065. list_move(&sp->link, invalid_list);
  2066. kvm_unaccount_mmu_page(kvm, sp);
  2067. } else {
  2068. /*
  2069. * Remove the active root from the active page list, the root
  2070. * will be explicitly freed when the root_count hits zero.
  2071. */
  2072. list_del(&sp->link);
  2073. /*
  2074. * Obsolete pages cannot be used on any vCPUs, see the comment
  2075. * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
  2076. * treats invalid shadow pages as being obsolete.
  2077. */
  2078. zapped_root = !is_obsolete_sp(kvm, sp);
  2079. }
  2080. if (sp->lpage_disallowed)
  2081. unaccount_huge_nx_page(kvm, sp);
  2082. sp->role.invalid = 1;
  2083. /*
  2084. * Make the request to free obsolete roots after marking the root
  2085. * invalid, otherwise other vCPUs may not see it as invalid.
  2086. */
  2087. if (zapped_root)
  2088. kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
  2089. return list_unstable;
  2090. }
  2091. static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  2092. struct list_head *invalid_list)
  2093. {
  2094. int nr_zapped;
  2095. __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
  2096. return nr_zapped;
  2097. }
  2098. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  2099. struct list_head *invalid_list)
  2100. {
  2101. struct kvm_mmu_page *sp, *nsp;
  2102. if (list_empty(invalid_list))
  2103. return;
  2104. /*
  2105. * We need to make sure everyone sees our modifications to
  2106. * the page tables and see changes to vcpu->mode here. The barrier
  2107. * in the kvm_flush_remote_tlbs() achieves this. This pairs
  2108. * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
  2109. *
  2110. * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
  2111. * guest mode and/or lockless shadow page table walks.
  2112. */
  2113. kvm_flush_remote_tlbs(kvm);
  2114. list_for_each_entry_safe(sp, nsp, invalid_list, link) {
  2115. WARN_ON(!sp->role.invalid || sp->root_count);
  2116. kvm_mmu_free_shadow_page(sp);
  2117. }
  2118. }
  2119. static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
  2120. unsigned long nr_to_zap)
  2121. {
  2122. unsigned long total_zapped = 0;
  2123. struct kvm_mmu_page *sp, *tmp;
  2124. LIST_HEAD(invalid_list);
  2125. bool unstable;
  2126. int nr_zapped;
  2127. if (list_empty(&kvm->arch.active_mmu_pages))
  2128. return 0;
  2129. restart:
  2130. list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
  2131. /*
  2132. * Don't zap active root pages, the page itself can't be freed
  2133. * and zapping it will just force vCPUs to realloc and reload.
  2134. */
  2135. if (sp->root_count)
  2136. continue;
  2137. unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
  2138. &nr_zapped);
  2139. total_zapped += nr_zapped;
  2140. if (total_zapped >= nr_to_zap)
  2141. break;
  2142. if (unstable)
  2143. goto restart;
  2144. }
  2145. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2146. kvm->stat.mmu_recycled += total_zapped;
  2147. return total_zapped;
  2148. }
  2149. static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
  2150. {
  2151. if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
  2152. return kvm->arch.n_max_mmu_pages -
  2153. kvm->arch.n_used_mmu_pages;
  2154. return 0;
  2155. }
  2156. static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
  2157. {
  2158. unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
  2159. if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
  2160. return 0;
  2161. kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
  2162. /*
  2163. * Note, this check is intentionally soft, it only guarantees that one
  2164. * page is available, while the caller may end up allocating as many as
  2165. * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
  2166. * exceeding the (arbitrary by default) limit will not harm the host,
  2167. * being too aggressive may unnecessarily kill the guest, and getting an
  2168. * exact count is far more trouble than it's worth, especially in the
  2169. * page fault paths.
  2170. */
  2171. if (!kvm_mmu_available_pages(vcpu->kvm))
  2172. return -ENOSPC;
  2173. return 0;
  2174. }
  2175. /*
  2176. * Changing the number of mmu pages allocated to the vm
  2177. * Note: if goal_nr_mmu_pages is too small, you will get dead lock
  2178. */
  2179. void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
  2180. {
  2181. write_lock(&kvm->mmu_lock);
  2182. if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
  2183. kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
  2184. goal_nr_mmu_pages);
  2185. goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
  2186. }
  2187. kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
  2188. write_unlock(&kvm->mmu_lock);
  2189. }
  2190. int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
  2191. {
  2192. struct kvm_mmu_page *sp;
  2193. LIST_HEAD(invalid_list);
  2194. int r;
  2195. pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
  2196. r = 0;
  2197. write_lock(&kvm->mmu_lock);
  2198. for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
  2199. pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
  2200. sp->role.word);
  2201. r = 1;
  2202. kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
  2203. }
  2204. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2205. write_unlock(&kvm->mmu_lock);
  2206. return r;
  2207. }
  2208. static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
  2209. {
  2210. gpa_t gpa;
  2211. int r;
  2212. if (vcpu->arch.mmu->root_role.direct)
  2213. return 0;
  2214. gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
  2215. r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  2216. return r;
  2217. }
  2218. static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  2219. {
  2220. trace_kvm_mmu_unsync_page(sp);
  2221. ++kvm->stat.mmu_unsync;
  2222. sp->unsync = 1;
  2223. kvm_mmu_mark_parents_unsync(sp);
  2224. }
  2225. /*
  2226. * Attempt to unsync any shadow pages that can be reached by the specified gfn,
  2227. * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
  2228. * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
  2229. * be write-protected.
  2230. */
  2231. int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
  2232. gfn_t gfn, bool can_unsync, bool prefetch)
  2233. {
  2234. struct kvm_mmu_page *sp;
  2235. bool locked = false;
  2236. /*
  2237. * Force write-protection if the page is being tracked. Note, the page
  2238. * track machinery is used to write-protect upper-level shadow pages,
  2239. * i.e. this guards the role.level == 4K assertion below!
  2240. */
  2241. if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
  2242. return -EPERM;
  2243. /*
  2244. * The page is not write-tracked, mark existing shadow pages unsync
  2245. * unless KVM is synchronizing an unsync SP (can_unsync = false). In
  2246. * that case, KVM must complete emulation of the guest TLB flush before
  2247. * allowing shadow pages to become unsync (writable by the guest).
  2248. */
  2249. for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
  2250. if (!can_unsync)
  2251. return -EPERM;
  2252. if (sp->unsync)
  2253. continue;
  2254. if (prefetch)
  2255. return -EEXIST;
  2256. /*
  2257. * TDP MMU page faults require an additional spinlock as they
  2258. * run with mmu_lock held for read, not write, and the unsync
  2259. * logic is not thread safe. Take the spinklock regardless of
  2260. * the MMU type to avoid extra conditionals/parameters, there's
  2261. * no meaningful penalty if mmu_lock is held for write.
  2262. */
  2263. if (!locked) {
  2264. locked = true;
  2265. spin_lock(&kvm->arch.mmu_unsync_pages_lock);
  2266. /*
  2267. * Recheck after taking the spinlock, a different vCPU
  2268. * may have since marked the page unsync. A false
  2269. * positive on the unprotected check above is not
  2270. * possible as clearing sp->unsync _must_ hold mmu_lock
  2271. * for write, i.e. unsync cannot transition from 0->1
  2272. * while this CPU holds mmu_lock for read (or write).
  2273. */
  2274. if (READ_ONCE(sp->unsync))
  2275. continue;
  2276. }
  2277. WARN_ON(sp->role.level != PG_LEVEL_4K);
  2278. kvm_unsync_page(kvm, sp);
  2279. }
  2280. if (locked)
  2281. spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
  2282. /*
  2283. * We need to ensure that the marking of unsync pages is visible
  2284. * before the SPTE is updated to allow writes because
  2285. * kvm_mmu_sync_roots() checks the unsync flags without holding
  2286. * the MMU lock and so can race with this. If the SPTE was updated
  2287. * before the page had been marked as unsync-ed, something like the
  2288. * following could happen:
  2289. *
  2290. * CPU 1 CPU 2
  2291. * ---------------------------------------------------------------------
  2292. * 1.2 Host updates SPTE
  2293. * to be writable
  2294. * 2.1 Guest writes a GPTE for GVA X.
  2295. * (GPTE being in the guest page table shadowed
  2296. * by the SP from CPU 1.)
  2297. * This reads SPTE during the page table walk.
  2298. * Since SPTE.W is read as 1, there is no
  2299. * fault.
  2300. *
  2301. * 2.2 Guest issues TLB flush.
  2302. * That causes a VM Exit.
  2303. *
  2304. * 2.3 Walking of unsync pages sees sp->unsync is
  2305. * false and skips the page.
  2306. *
  2307. * 2.4 Guest accesses GVA X.
  2308. * Since the mapping in the SP was not updated,
  2309. * so the old mapping for GVA X incorrectly
  2310. * gets used.
  2311. * 1.1 Host marks SP
  2312. * as unsync
  2313. * (sp->unsync = true)
  2314. *
  2315. * The write barrier below ensures that 1.1 happens before 1.2 and thus
  2316. * the situation in 2.4 does not arise. It pairs with the read barrier
  2317. * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
  2318. */
  2319. smp_wmb();
  2320. return 0;
  2321. }
  2322. static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
  2323. u64 *sptep, unsigned int pte_access, gfn_t gfn,
  2324. kvm_pfn_t pfn, struct kvm_page_fault *fault)
  2325. {
  2326. struct kvm_mmu_page *sp = sptep_to_sp(sptep);
  2327. int level = sp->role.level;
  2328. int was_rmapped = 0;
  2329. int ret = RET_PF_FIXED;
  2330. bool flush = false;
  2331. bool wrprot;
  2332. u64 spte;
  2333. /* Prefetching always gets a writable pfn. */
  2334. bool host_writable = !fault || fault->map_writable;
  2335. bool prefetch = !fault || fault->prefetch;
  2336. bool write_fault = fault && fault->write;
  2337. pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
  2338. *sptep, write_fault, gfn);
  2339. if (unlikely(is_noslot_pfn(pfn))) {
  2340. vcpu->stat.pf_mmio_spte_created++;
  2341. mark_mmio_spte(vcpu, sptep, gfn, pte_access);
  2342. return RET_PF_EMULATE;
  2343. }
  2344. if (is_shadow_present_pte(*sptep)) {
  2345. /*
  2346. * If we overwrite a PTE page pointer with a 2MB PMD, unlink
  2347. * the parent of the now unreachable PTE.
  2348. */
  2349. if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
  2350. struct kvm_mmu_page *child;
  2351. u64 pte = *sptep;
  2352. child = to_shadow_page(pte & SPTE_BASE_ADDR_MASK);
  2353. drop_parent_pte(child, sptep);
  2354. flush = true;
  2355. } else if (pfn != spte_to_pfn(*sptep)) {
  2356. pgprintk("hfn old %llx new %llx\n",
  2357. spte_to_pfn(*sptep), pfn);
  2358. drop_spte(vcpu->kvm, sptep);
  2359. flush = true;
  2360. } else
  2361. was_rmapped = 1;
  2362. }
  2363. wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
  2364. true, host_writable, &spte);
  2365. if (*sptep == spte) {
  2366. ret = RET_PF_SPURIOUS;
  2367. } else {
  2368. flush |= mmu_spte_update(sptep, spte);
  2369. trace_kvm_mmu_set_spte(level, gfn, sptep);
  2370. }
  2371. if (wrprot) {
  2372. if (write_fault)
  2373. ret = RET_PF_EMULATE;
  2374. }
  2375. if (flush)
  2376. kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
  2377. KVM_PAGES_PER_HPAGE(level));
  2378. pgprintk("%s: setting spte %llx\n", __func__, *sptep);
  2379. if (!was_rmapped) {
  2380. WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
  2381. rmap_add(vcpu, slot, sptep, gfn, pte_access);
  2382. } else {
  2383. /* Already rmapped but the pte_access bits may have changed. */
  2384. kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
  2385. }
  2386. return ret;
  2387. }
  2388. static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
  2389. struct kvm_mmu_page *sp,
  2390. u64 *start, u64 *end)
  2391. {
  2392. struct page *pages[PTE_PREFETCH_NUM];
  2393. struct kvm_memory_slot *slot;
  2394. unsigned int access = sp->role.access;
  2395. int i, ret;
  2396. gfn_t gfn;
  2397. gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
  2398. slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
  2399. if (!slot)
  2400. return -1;
  2401. ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
  2402. if (ret <= 0)
  2403. return -1;
  2404. for (i = 0; i < ret; i++, gfn++, start++) {
  2405. mmu_set_spte(vcpu, slot, start, access, gfn,
  2406. page_to_pfn(pages[i]), NULL);
  2407. put_page(pages[i]);
  2408. }
  2409. return 0;
  2410. }
  2411. static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
  2412. struct kvm_mmu_page *sp, u64 *sptep)
  2413. {
  2414. u64 *spte, *start = NULL;
  2415. int i;
  2416. WARN_ON(!sp->role.direct);
  2417. i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
  2418. spte = sp->spt + i;
  2419. for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
  2420. if (is_shadow_present_pte(*spte) || spte == sptep) {
  2421. if (!start)
  2422. continue;
  2423. if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
  2424. return;
  2425. start = NULL;
  2426. } else if (!start)
  2427. start = spte;
  2428. }
  2429. if (start)
  2430. direct_pte_prefetch_many(vcpu, sp, start, spte);
  2431. }
  2432. static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
  2433. {
  2434. struct kvm_mmu_page *sp;
  2435. sp = sptep_to_sp(sptep);
  2436. /*
  2437. * Without accessed bits, there's no way to distinguish between
  2438. * actually accessed translations and prefetched, so disable pte
  2439. * prefetch if accessed bits aren't available.
  2440. */
  2441. if (sp_ad_disabled(sp))
  2442. return;
  2443. if (sp->role.level > PG_LEVEL_4K)
  2444. return;
  2445. /*
  2446. * If addresses are being invalidated, skip prefetching to avoid
  2447. * accidentally prefetching those addresses.
  2448. */
  2449. if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
  2450. return;
  2451. __direct_pte_prefetch(vcpu, sp, sptep);
  2452. }
  2453. /*
  2454. * Lookup the mapping level for @gfn in the current mm.
  2455. *
  2456. * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
  2457. * consumer to be tied into KVM's handlers for MMU notifier events!
  2458. *
  2459. * There are several ways to safely use this helper:
  2460. *
  2461. * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
  2462. * consuming it. In this case, mmu_lock doesn't need to be held during the
  2463. * lookup, but it does need to be held while checking the MMU notifier.
  2464. *
  2465. * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
  2466. * event for the hva. This can be done by explicit checking the MMU notifier
  2467. * or by ensuring that KVM already has a valid mapping that covers the hva.
  2468. *
  2469. * - Do not use the result to install new mappings, e.g. use the host mapping
  2470. * level only to decide whether or not to zap an entry. In this case, it's
  2471. * not required to hold mmu_lock (though it's highly likely the caller will
  2472. * want to hold mmu_lock anyways, e.g. to modify SPTEs).
  2473. *
  2474. * Note! The lookup can still race with modifications to host page tables, but
  2475. * the above "rules" ensure KVM will not _consume_ the result of the walk if a
  2476. * race with the primary MMU occurs.
  2477. */
  2478. static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
  2479. const struct kvm_memory_slot *slot)
  2480. {
  2481. int level = PG_LEVEL_4K;
  2482. unsigned long hva;
  2483. unsigned long flags;
  2484. pgd_t pgd;
  2485. p4d_t p4d;
  2486. pud_t pud;
  2487. pmd_t pmd;
  2488. /*
  2489. * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
  2490. * is not solely for performance, it's also necessary to avoid the
  2491. * "writable" check in __gfn_to_hva_many(), which will always fail on
  2492. * read-only memslots due to gfn_to_hva() assuming writes. Earlier
  2493. * page fault steps have already verified the guest isn't writing a
  2494. * read-only memslot.
  2495. */
  2496. hva = __gfn_to_hva_memslot(slot, gfn);
  2497. /*
  2498. * Disable IRQs to prevent concurrent tear down of host page tables,
  2499. * e.g. if the primary MMU promotes a P*D to a huge page and then frees
  2500. * the original page table.
  2501. */
  2502. local_irq_save(flags);
  2503. /*
  2504. * Read each entry once. As above, a non-leaf entry can be promoted to
  2505. * a huge page _during_ this walk. Re-reading the entry could send the
  2506. * walk into the weeks, e.g. p*d_large() returns false (sees the old
  2507. * value) and then p*d_offset() walks into the target huge page instead
  2508. * of the old page table (sees the new value).
  2509. */
  2510. pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
  2511. if (pgd_none(pgd))
  2512. goto out;
  2513. p4d = READ_ONCE(*p4d_offset(&pgd, hva));
  2514. if (p4d_none(p4d) || !p4d_present(p4d))
  2515. goto out;
  2516. pud = READ_ONCE(*pud_offset(&p4d, hva));
  2517. if (pud_none(pud) || !pud_present(pud))
  2518. goto out;
  2519. if (pud_large(pud)) {
  2520. level = PG_LEVEL_1G;
  2521. goto out;
  2522. }
  2523. pmd = READ_ONCE(*pmd_offset(&pud, hva));
  2524. if (pmd_none(pmd) || !pmd_present(pmd))
  2525. goto out;
  2526. if (pmd_large(pmd))
  2527. level = PG_LEVEL_2M;
  2528. out:
  2529. local_irq_restore(flags);
  2530. return level;
  2531. }
  2532. int kvm_mmu_max_mapping_level(struct kvm *kvm,
  2533. const struct kvm_memory_slot *slot, gfn_t gfn,
  2534. int max_level)
  2535. {
  2536. struct kvm_lpage_info *linfo;
  2537. int host_level;
  2538. max_level = min(max_level, max_huge_page_level);
  2539. for ( ; max_level > PG_LEVEL_4K; max_level--) {
  2540. linfo = lpage_info_slot(gfn, slot, max_level);
  2541. if (!linfo->disallow_lpage)
  2542. break;
  2543. }
  2544. if (max_level == PG_LEVEL_4K)
  2545. return PG_LEVEL_4K;
  2546. host_level = host_pfn_mapping_level(kvm, gfn, slot);
  2547. return min(host_level, max_level);
  2548. }
  2549. void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  2550. {
  2551. struct kvm_memory_slot *slot = fault->slot;
  2552. kvm_pfn_t mask;
  2553. fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
  2554. if (unlikely(fault->max_level == PG_LEVEL_4K))
  2555. return;
  2556. if (is_error_noslot_pfn(fault->pfn))
  2557. return;
  2558. if (kvm_slot_dirty_track_enabled(slot))
  2559. return;
  2560. /*
  2561. * Enforce the iTLB multihit workaround after capturing the requested
  2562. * level, which will be used to do precise, accurate accounting.
  2563. */
  2564. fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
  2565. fault->gfn, fault->max_level);
  2566. if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
  2567. return;
  2568. /*
  2569. * mmu_invalidate_retry() was successful and mmu_lock is held, so
  2570. * the pmd can't be split from under us.
  2571. */
  2572. fault->goal_level = fault->req_level;
  2573. mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
  2574. VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
  2575. fault->pfn &= ~mask;
  2576. }
  2577. void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
  2578. {
  2579. if (cur_level > PG_LEVEL_4K &&
  2580. cur_level == fault->goal_level &&
  2581. is_shadow_present_pte(spte) &&
  2582. !is_large_pte(spte)) {
  2583. /*
  2584. * A small SPTE exists for this pfn, but FNAME(fetch)
  2585. * and __direct_map would like to create a large PTE
  2586. * instead: just force them to go down another level,
  2587. * patching back for them into pfn the next 9 bits of
  2588. * the address.
  2589. */
  2590. u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
  2591. KVM_PAGES_PER_HPAGE(cur_level - 1);
  2592. fault->pfn |= fault->gfn & page_mask;
  2593. fault->goal_level--;
  2594. }
  2595. }
  2596. static int __direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  2597. {
  2598. struct kvm_shadow_walk_iterator it;
  2599. struct kvm_mmu_page *sp;
  2600. int ret;
  2601. gfn_t base_gfn = fault->gfn;
  2602. kvm_mmu_hugepage_adjust(vcpu, fault);
  2603. trace_kvm_mmu_spte_requested(fault);
  2604. for_each_shadow_entry(vcpu, fault->addr, it) {
  2605. /*
  2606. * We cannot overwrite existing page tables with an NX
  2607. * large page, as the leaf could be executable.
  2608. */
  2609. if (fault->nx_huge_page_workaround_enabled)
  2610. disallowed_hugepage_adjust(fault, *it.sptep, it.level);
  2611. base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
  2612. if (it.level == fault->goal_level)
  2613. break;
  2614. sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
  2615. if (sp == ERR_PTR(-EEXIST))
  2616. continue;
  2617. link_shadow_page(vcpu, it.sptep, sp);
  2618. if (fault->is_tdp && fault->huge_page_disallowed &&
  2619. fault->req_level >= it.level)
  2620. account_huge_nx_page(vcpu->kvm, sp);
  2621. }
  2622. if (WARN_ON_ONCE(it.level != fault->goal_level))
  2623. return -EFAULT;
  2624. ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
  2625. base_gfn, fault->pfn, fault);
  2626. if (ret == RET_PF_SPURIOUS)
  2627. return ret;
  2628. direct_pte_prefetch(vcpu, it.sptep);
  2629. return ret;
  2630. }
  2631. static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
  2632. {
  2633. send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
  2634. }
  2635. static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
  2636. {
  2637. /*
  2638. * Do not cache the mmio info caused by writing the readonly gfn
  2639. * into the spte otherwise read access on readonly gfn also can
  2640. * caused mmio page fault and treat it as mmio access.
  2641. */
  2642. if (pfn == KVM_PFN_ERR_RO_FAULT)
  2643. return RET_PF_EMULATE;
  2644. if (pfn == KVM_PFN_ERR_HWPOISON) {
  2645. kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
  2646. return RET_PF_RETRY;
  2647. }
  2648. return -EFAULT;
  2649. }
  2650. static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
  2651. unsigned int access)
  2652. {
  2653. /* The pfn is invalid, report the error! */
  2654. if (unlikely(is_error_pfn(fault->pfn)))
  2655. return kvm_handle_bad_page(vcpu, fault->gfn, fault->pfn);
  2656. if (unlikely(!fault->slot)) {
  2657. gva_t gva = fault->is_tdp ? 0 : fault->addr;
  2658. vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
  2659. access & shadow_mmio_access_mask);
  2660. /*
  2661. * If MMIO caching is disabled, emulate immediately without
  2662. * touching the shadow page tables as attempting to install an
  2663. * MMIO SPTE will just be an expensive nop. Do not cache MMIO
  2664. * whose gfn is greater than host.MAXPHYADDR, any guest that
  2665. * generates such gfns is running nested and is being tricked
  2666. * by L0 userspace (you can observe gfn > L1.MAXPHYADDR if
  2667. * and only if L1's MAXPHYADDR is inaccurate with respect to
  2668. * the hardware's).
  2669. */
  2670. if (unlikely(!enable_mmio_caching) ||
  2671. unlikely(fault->gfn > kvm_mmu_max_gfn()))
  2672. return RET_PF_EMULATE;
  2673. }
  2674. return RET_PF_CONTINUE;
  2675. }
  2676. static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
  2677. {
  2678. /*
  2679. * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
  2680. * reach the common page fault handler if the SPTE has an invalid MMIO
  2681. * generation number. Refreshing the MMIO generation needs to go down
  2682. * the slow path. Note, EPT Misconfigs do NOT set the PRESENT flag!
  2683. */
  2684. if (fault->rsvd)
  2685. return false;
  2686. /*
  2687. * #PF can be fast if:
  2688. *
  2689. * 1. The shadow page table entry is not present and A/D bits are
  2690. * disabled _by KVM_, which could mean that the fault is potentially
  2691. * caused by access tracking (if enabled). If A/D bits are enabled
  2692. * by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
  2693. * bits for L2 and employ access tracking, but the fast page fault
  2694. * mechanism only supports direct MMUs.
  2695. * 2. The shadow page table entry is present, the access is a write,
  2696. * and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
  2697. * the fault was caused by a write-protection violation. If the
  2698. * SPTE is MMU-writable (determined later), the fault can be fixed
  2699. * by setting the Writable bit, which can be done out of mmu_lock.
  2700. */
  2701. if (!fault->present)
  2702. return !kvm_ad_enabled();
  2703. /*
  2704. * Note, instruction fetches and writes are mutually exclusive, ignore
  2705. * the "exec" flag.
  2706. */
  2707. return fault->write;
  2708. }
  2709. /*
  2710. * Returns true if the SPTE was fixed successfully. Otherwise,
  2711. * someone else modified the SPTE from its original value.
  2712. */
  2713. static bool
  2714. fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
  2715. u64 *sptep, u64 old_spte, u64 new_spte)
  2716. {
  2717. /*
  2718. * Theoretically we could also set dirty bit (and flush TLB) here in
  2719. * order to eliminate unnecessary PML logging. See comments in
  2720. * set_spte. But fast_page_fault is very unlikely to happen with PML
  2721. * enabled, so we do not do this. This might result in the same GPA
  2722. * to be logged in PML buffer again when the write really happens, and
  2723. * eventually to be called by mark_page_dirty twice. But it's also no
  2724. * harm. This also avoids the TLB flush needed after setting dirty bit
  2725. * so non-PML cases won't be impacted.
  2726. *
  2727. * Compare with set_spte where instead shadow_dirty_mask is set.
  2728. */
  2729. if (!try_cmpxchg64(sptep, &old_spte, new_spte))
  2730. return false;
  2731. if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
  2732. mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
  2733. return true;
  2734. }
  2735. static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
  2736. {
  2737. if (fault->exec)
  2738. return is_executable_pte(spte);
  2739. if (fault->write)
  2740. return is_writable_pte(spte);
  2741. /* Fault was on Read access */
  2742. return spte & PT_PRESENT_MASK;
  2743. }
  2744. /*
  2745. * Returns the last level spte pointer of the shadow page walk for the given
  2746. * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
  2747. * walk could be performed, returns NULL and *spte does not contain valid data.
  2748. *
  2749. * Contract:
  2750. * - Must be called between walk_shadow_page_lockless_{begin,end}.
  2751. * - The returned sptep must not be used after walk_shadow_page_lockless_end.
  2752. */
  2753. static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
  2754. {
  2755. struct kvm_shadow_walk_iterator iterator;
  2756. u64 old_spte;
  2757. u64 *sptep = NULL;
  2758. for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
  2759. sptep = iterator.sptep;
  2760. *spte = old_spte;
  2761. }
  2762. return sptep;
  2763. }
  2764. /*
  2765. * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
  2766. */
  2767. static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  2768. {
  2769. struct kvm_mmu_page *sp;
  2770. int ret = RET_PF_INVALID;
  2771. u64 spte = 0ull;
  2772. u64 *sptep = NULL;
  2773. uint retry_count = 0;
  2774. if (!page_fault_can_be_fast(fault))
  2775. return ret;
  2776. walk_shadow_page_lockless_begin(vcpu);
  2777. do {
  2778. u64 new_spte;
  2779. if (is_tdp_mmu(vcpu->arch.mmu))
  2780. sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
  2781. else
  2782. sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
  2783. if (!is_shadow_present_pte(spte))
  2784. break;
  2785. sp = sptep_to_sp(sptep);
  2786. if (!is_last_spte(spte, sp->role.level))
  2787. break;
  2788. /*
  2789. * Check whether the memory access that caused the fault would
  2790. * still cause it if it were to be performed right now. If not,
  2791. * then this is a spurious fault caused by TLB lazily flushed,
  2792. * or some other CPU has already fixed the PTE after the
  2793. * current CPU took the fault.
  2794. *
  2795. * Need not check the access of upper level table entries since
  2796. * they are always ACC_ALL.
  2797. */
  2798. if (is_access_allowed(fault, spte)) {
  2799. ret = RET_PF_SPURIOUS;
  2800. break;
  2801. }
  2802. new_spte = spte;
  2803. /*
  2804. * KVM only supports fixing page faults outside of MMU lock for
  2805. * direct MMUs, nested MMUs are always indirect, and KVM always
  2806. * uses A/D bits for non-nested MMUs. Thus, if A/D bits are
  2807. * enabled, the SPTE can't be an access-tracked SPTE.
  2808. */
  2809. if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
  2810. new_spte = restore_acc_track_spte(new_spte);
  2811. /*
  2812. * To keep things simple, only SPTEs that are MMU-writable can
  2813. * be made fully writable outside of mmu_lock, e.g. only SPTEs
  2814. * that were write-protected for dirty-logging or access
  2815. * tracking are handled here. Don't bother checking if the
  2816. * SPTE is writable to prioritize running with A/D bits enabled.
  2817. * The is_access_allowed() check above handles the common case
  2818. * of the fault being spurious, and the SPTE is known to be
  2819. * shadow-present, i.e. except for access tracking restoration
  2820. * making the new SPTE writable, the check is wasteful.
  2821. */
  2822. if (fault->write && is_mmu_writable_spte(spte)) {
  2823. new_spte |= PT_WRITABLE_MASK;
  2824. /*
  2825. * Do not fix write-permission on the large spte when
  2826. * dirty logging is enabled. Since we only dirty the
  2827. * first page into the dirty-bitmap in
  2828. * fast_pf_fix_direct_spte(), other pages are missed
  2829. * if its slot has dirty logging enabled.
  2830. *
  2831. * Instead, we let the slow page fault path create a
  2832. * normal spte to fix the access.
  2833. */
  2834. if (sp->role.level > PG_LEVEL_4K &&
  2835. kvm_slot_dirty_track_enabled(fault->slot))
  2836. break;
  2837. }
  2838. /* Verify that the fault can be handled in the fast path */
  2839. if (new_spte == spte ||
  2840. !is_access_allowed(fault, new_spte))
  2841. break;
  2842. /*
  2843. * Currently, fast page fault only works for direct mapping
  2844. * since the gfn is not stable for indirect shadow page. See
  2845. * Documentation/virt/kvm/locking.rst to get more detail.
  2846. */
  2847. if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
  2848. ret = RET_PF_FIXED;
  2849. break;
  2850. }
  2851. if (++retry_count > 4) {
  2852. printk_once(KERN_WARNING
  2853. "kvm: Fast #PF retrying more than 4 times.\n");
  2854. break;
  2855. }
  2856. } while (true);
  2857. trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
  2858. walk_shadow_page_lockless_end(vcpu);
  2859. if (ret != RET_PF_INVALID)
  2860. vcpu->stat.pf_fast++;
  2861. return ret;
  2862. }
  2863. static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
  2864. struct list_head *invalid_list)
  2865. {
  2866. struct kvm_mmu_page *sp;
  2867. if (!VALID_PAGE(*root_hpa))
  2868. return;
  2869. sp = to_shadow_page(*root_hpa & SPTE_BASE_ADDR_MASK);
  2870. if (WARN_ON(!sp))
  2871. return;
  2872. if (is_tdp_mmu_page(sp))
  2873. kvm_tdp_mmu_put_root(kvm, sp, false);
  2874. else if (!--sp->root_count && sp->role.invalid)
  2875. kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2876. *root_hpa = INVALID_PAGE;
  2877. }
  2878. /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
  2879. void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
  2880. ulong roots_to_free)
  2881. {
  2882. int i;
  2883. LIST_HEAD(invalid_list);
  2884. bool free_active_root;
  2885. BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
  2886. /* Before acquiring the MMU lock, see if we need to do any real work. */
  2887. free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
  2888. && VALID_PAGE(mmu->root.hpa);
  2889. if (!free_active_root) {
  2890. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  2891. if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
  2892. VALID_PAGE(mmu->prev_roots[i].hpa))
  2893. break;
  2894. if (i == KVM_MMU_NUM_PREV_ROOTS)
  2895. return;
  2896. }
  2897. write_lock(&kvm->mmu_lock);
  2898. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  2899. if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
  2900. mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
  2901. &invalid_list);
  2902. if (free_active_root) {
  2903. if (to_shadow_page(mmu->root.hpa)) {
  2904. mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
  2905. } else if (mmu->pae_root) {
  2906. for (i = 0; i < 4; ++i) {
  2907. if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
  2908. continue;
  2909. mmu_free_root_page(kvm, &mmu->pae_root[i],
  2910. &invalid_list);
  2911. mmu->pae_root[i] = INVALID_PAE_ROOT;
  2912. }
  2913. }
  2914. mmu->root.hpa = INVALID_PAGE;
  2915. mmu->root.pgd = 0;
  2916. }
  2917. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2918. write_unlock(&kvm->mmu_lock);
  2919. }
  2920. EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
  2921. void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
  2922. {
  2923. unsigned long roots_to_free = 0;
  2924. hpa_t root_hpa;
  2925. int i;
  2926. /*
  2927. * This should not be called while L2 is active, L2 can't invalidate
  2928. * _only_ its own roots, e.g. INVVPID unconditionally exits.
  2929. */
  2930. WARN_ON_ONCE(mmu->root_role.guest_mode);
  2931. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  2932. root_hpa = mmu->prev_roots[i].hpa;
  2933. if (!VALID_PAGE(root_hpa))
  2934. continue;
  2935. if (!to_shadow_page(root_hpa) ||
  2936. to_shadow_page(root_hpa)->role.guest_mode)
  2937. roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
  2938. }
  2939. kvm_mmu_free_roots(kvm, mmu, roots_to_free);
  2940. }
  2941. EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
  2942. static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
  2943. {
  2944. int ret = 0;
  2945. if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
  2946. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2947. ret = 1;
  2948. }
  2949. return ret;
  2950. }
  2951. static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
  2952. u8 level)
  2953. {
  2954. union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
  2955. struct kvm_mmu_page *sp;
  2956. role.level = level;
  2957. role.quadrant = quadrant;
  2958. WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
  2959. WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
  2960. sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
  2961. ++sp->root_count;
  2962. return __pa(sp->spt);
  2963. }
  2964. static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
  2965. {
  2966. struct kvm_mmu *mmu = vcpu->arch.mmu;
  2967. u8 shadow_root_level = mmu->root_role.level;
  2968. hpa_t root;
  2969. unsigned i;
  2970. int r;
  2971. write_lock(&vcpu->kvm->mmu_lock);
  2972. r = make_mmu_pages_available(vcpu);
  2973. if (r < 0)
  2974. goto out_unlock;
  2975. if (is_tdp_mmu_enabled(vcpu->kvm)) {
  2976. root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
  2977. mmu->root.hpa = root;
  2978. } else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
  2979. root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
  2980. mmu->root.hpa = root;
  2981. } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
  2982. if (WARN_ON_ONCE(!mmu->pae_root)) {
  2983. r = -EIO;
  2984. goto out_unlock;
  2985. }
  2986. for (i = 0; i < 4; ++i) {
  2987. WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
  2988. root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
  2989. PT32_ROOT_LEVEL);
  2990. mmu->pae_root[i] = root | PT_PRESENT_MASK |
  2991. shadow_me_value;
  2992. }
  2993. mmu->root.hpa = __pa(mmu->pae_root);
  2994. } else {
  2995. WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
  2996. r = -EIO;
  2997. goto out_unlock;
  2998. }
  2999. /* root.pgd is ignored for direct MMUs. */
  3000. mmu->root.pgd = 0;
  3001. out_unlock:
  3002. write_unlock(&vcpu->kvm->mmu_lock);
  3003. return r;
  3004. }
  3005. static int mmu_first_shadow_root_alloc(struct kvm *kvm)
  3006. {
  3007. struct kvm_memslots *slots;
  3008. struct kvm_memory_slot *slot;
  3009. int r = 0, i, bkt;
  3010. /*
  3011. * Check if this is the first shadow root being allocated before
  3012. * taking the lock.
  3013. */
  3014. if (kvm_shadow_root_allocated(kvm))
  3015. return 0;
  3016. mutex_lock(&kvm->slots_arch_lock);
  3017. /* Recheck, under the lock, whether this is the first shadow root. */
  3018. if (kvm_shadow_root_allocated(kvm))
  3019. goto out_unlock;
  3020. /*
  3021. * Check if anything actually needs to be allocated, e.g. all metadata
  3022. * will be allocated upfront if TDP is disabled.
  3023. */
  3024. if (kvm_memslots_have_rmaps(kvm) &&
  3025. kvm_page_track_write_tracking_enabled(kvm))
  3026. goto out_success;
  3027. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  3028. slots = __kvm_memslots(kvm, i);
  3029. kvm_for_each_memslot(slot, bkt, slots) {
  3030. /*
  3031. * Both of these functions are no-ops if the target is
  3032. * already allocated, so unconditionally calling both
  3033. * is safe. Intentionally do NOT free allocations on
  3034. * failure to avoid having to track which allocations
  3035. * were made now versus when the memslot was created.
  3036. * The metadata is guaranteed to be freed when the slot
  3037. * is freed, and will be kept/used if userspace retries
  3038. * KVM_RUN instead of killing the VM.
  3039. */
  3040. r = memslot_rmap_alloc(slot, slot->npages);
  3041. if (r)
  3042. goto out_unlock;
  3043. r = kvm_page_track_write_tracking_alloc(slot);
  3044. if (r)
  3045. goto out_unlock;
  3046. }
  3047. }
  3048. /*
  3049. * Ensure that shadow_root_allocated becomes true strictly after
  3050. * all the related pointers are set.
  3051. */
  3052. out_success:
  3053. smp_store_release(&kvm->arch.shadow_root_allocated, true);
  3054. out_unlock:
  3055. mutex_unlock(&kvm->slots_arch_lock);
  3056. return r;
  3057. }
  3058. static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
  3059. {
  3060. struct kvm_mmu *mmu = vcpu->arch.mmu;
  3061. u64 pdptrs[4], pm_mask;
  3062. gfn_t root_gfn, root_pgd;
  3063. int quadrant, i, r;
  3064. hpa_t root;
  3065. root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
  3066. root_gfn = root_pgd >> PAGE_SHIFT;
  3067. if (mmu_check_root(vcpu, root_gfn))
  3068. return 1;
  3069. /*
  3070. * On SVM, reading PDPTRs might access guest memory, which might fault
  3071. * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
  3072. */
  3073. if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
  3074. for (i = 0; i < 4; ++i) {
  3075. pdptrs[i] = mmu->get_pdptr(vcpu, i);
  3076. if (!(pdptrs[i] & PT_PRESENT_MASK))
  3077. continue;
  3078. if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
  3079. return 1;
  3080. }
  3081. }
  3082. r = mmu_first_shadow_root_alloc(vcpu->kvm);
  3083. if (r)
  3084. return r;
  3085. write_lock(&vcpu->kvm->mmu_lock);
  3086. r = make_mmu_pages_available(vcpu);
  3087. if (r < 0)
  3088. goto out_unlock;
  3089. /*
  3090. * Do we shadow a long mode page table? If so we need to
  3091. * write-protect the guests page table root.
  3092. */
  3093. if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
  3094. root = mmu_alloc_root(vcpu, root_gfn, 0,
  3095. mmu->root_role.level);
  3096. mmu->root.hpa = root;
  3097. goto set_root_pgd;
  3098. }
  3099. if (WARN_ON_ONCE(!mmu->pae_root)) {
  3100. r = -EIO;
  3101. goto out_unlock;
  3102. }
  3103. /*
  3104. * We shadow a 32 bit page table. This may be a legacy 2-level
  3105. * or a PAE 3-level page table. In either case we need to be aware that
  3106. * the shadow page table may be a PAE or a long mode page table.
  3107. */
  3108. pm_mask = PT_PRESENT_MASK | shadow_me_value;
  3109. if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
  3110. pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
  3111. if (WARN_ON_ONCE(!mmu->pml4_root)) {
  3112. r = -EIO;
  3113. goto out_unlock;
  3114. }
  3115. mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
  3116. if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
  3117. if (WARN_ON_ONCE(!mmu->pml5_root)) {
  3118. r = -EIO;
  3119. goto out_unlock;
  3120. }
  3121. mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
  3122. }
  3123. }
  3124. for (i = 0; i < 4; ++i) {
  3125. WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
  3126. if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
  3127. if (!(pdptrs[i] & PT_PRESENT_MASK)) {
  3128. mmu->pae_root[i] = INVALID_PAE_ROOT;
  3129. continue;
  3130. }
  3131. root_gfn = pdptrs[i] >> PAGE_SHIFT;
  3132. }
  3133. /*
  3134. * If shadowing 32-bit non-PAE page tables, each PAE page
  3135. * directory maps one quarter of the guest's non-PAE page
  3136. * directory. Othwerise each PAE page direct shadows one guest
  3137. * PAE page directory so that quadrant should be 0.
  3138. */
  3139. quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
  3140. root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
  3141. mmu->pae_root[i] = root | pm_mask;
  3142. }
  3143. if (mmu->root_role.level == PT64_ROOT_5LEVEL)
  3144. mmu->root.hpa = __pa(mmu->pml5_root);
  3145. else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
  3146. mmu->root.hpa = __pa(mmu->pml4_root);
  3147. else
  3148. mmu->root.hpa = __pa(mmu->pae_root);
  3149. set_root_pgd:
  3150. mmu->root.pgd = root_pgd;
  3151. out_unlock:
  3152. write_unlock(&vcpu->kvm->mmu_lock);
  3153. return r;
  3154. }
  3155. static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
  3156. {
  3157. struct kvm_mmu *mmu = vcpu->arch.mmu;
  3158. bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
  3159. u64 *pml5_root = NULL;
  3160. u64 *pml4_root = NULL;
  3161. u64 *pae_root;
  3162. /*
  3163. * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
  3164. * tables are allocated and initialized at root creation as there is no
  3165. * equivalent level in the guest's NPT to shadow. Allocate the tables
  3166. * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
  3167. */
  3168. if (mmu->root_role.direct ||
  3169. mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
  3170. mmu->root_role.level < PT64_ROOT_4LEVEL)
  3171. return 0;
  3172. /*
  3173. * NPT, the only paging mode that uses this horror, uses a fixed number
  3174. * of levels for the shadow page tables, e.g. all MMUs are 4-level or
  3175. * all MMus are 5-level. Thus, this can safely require that pml5_root
  3176. * is allocated if the other roots are valid and pml5 is needed, as any
  3177. * prior MMU would also have required pml5.
  3178. */
  3179. if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
  3180. return 0;
  3181. /*
  3182. * The special roots should always be allocated in concert. Yell and
  3183. * bail if KVM ends up in a state where only one of the roots is valid.
  3184. */
  3185. if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
  3186. (need_pml5 && mmu->pml5_root)))
  3187. return -EIO;
  3188. /*
  3189. * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
  3190. * doesn't need to be decrypted.
  3191. */
  3192. pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
  3193. if (!pae_root)
  3194. return -ENOMEM;
  3195. #ifdef CONFIG_X86_64
  3196. pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
  3197. if (!pml4_root)
  3198. goto err_pml4;
  3199. if (need_pml5) {
  3200. pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
  3201. if (!pml5_root)
  3202. goto err_pml5;
  3203. }
  3204. #endif
  3205. mmu->pae_root = pae_root;
  3206. mmu->pml4_root = pml4_root;
  3207. mmu->pml5_root = pml5_root;
  3208. return 0;
  3209. #ifdef CONFIG_X86_64
  3210. err_pml5:
  3211. free_page((unsigned long)pml4_root);
  3212. err_pml4:
  3213. free_page((unsigned long)pae_root);
  3214. return -ENOMEM;
  3215. #endif
  3216. }
  3217. static bool is_unsync_root(hpa_t root)
  3218. {
  3219. struct kvm_mmu_page *sp;
  3220. if (!VALID_PAGE(root))
  3221. return false;
  3222. /*
  3223. * The read barrier orders the CPU's read of SPTE.W during the page table
  3224. * walk before the reads of sp->unsync/sp->unsync_children here.
  3225. *
  3226. * Even if another CPU was marking the SP as unsync-ed simultaneously,
  3227. * any guest page table changes are not guaranteed to be visible anyway
  3228. * until this VCPU issues a TLB flush strictly after those changes are
  3229. * made. We only need to ensure that the other CPU sets these flags
  3230. * before any actual changes to the page tables are made. The comments
  3231. * in mmu_try_to_unsync_pages() describe what could go wrong if this
  3232. * requirement isn't satisfied.
  3233. */
  3234. smp_rmb();
  3235. sp = to_shadow_page(root);
  3236. /*
  3237. * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
  3238. * PDPTEs for a given PAE root need to be synchronized individually.
  3239. */
  3240. if (WARN_ON_ONCE(!sp))
  3241. return false;
  3242. if (sp->unsync || sp->unsync_children)
  3243. return true;
  3244. return false;
  3245. }
  3246. void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
  3247. {
  3248. int i;
  3249. struct kvm_mmu_page *sp;
  3250. if (vcpu->arch.mmu->root_role.direct)
  3251. return;
  3252. if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
  3253. return;
  3254. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  3255. if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
  3256. hpa_t root = vcpu->arch.mmu->root.hpa;
  3257. sp = to_shadow_page(root);
  3258. if (!is_unsync_root(root))
  3259. return;
  3260. write_lock(&vcpu->kvm->mmu_lock);
  3261. mmu_sync_children(vcpu, sp, true);
  3262. write_unlock(&vcpu->kvm->mmu_lock);
  3263. return;
  3264. }
  3265. write_lock(&vcpu->kvm->mmu_lock);
  3266. for (i = 0; i < 4; ++i) {
  3267. hpa_t root = vcpu->arch.mmu->pae_root[i];
  3268. if (IS_VALID_PAE_ROOT(root)) {
  3269. root &= SPTE_BASE_ADDR_MASK;
  3270. sp = to_shadow_page(root);
  3271. mmu_sync_children(vcpu, sp, true);
  3272. }
  3273. }
  3274. write_unlock(&vcpu->kvm->mmu_lock);
  3275. }
  3276. void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
  3277. {
  3278. unsigned long roots_to_free = 0;
  3279. int i;
  3280. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  3281. if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
  3282. roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
  3283. /* sync prev_roots by simply freeing them */
  3284. kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
  3285. }
  3286. static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  3287. gpa_t vaddr, u64 access,
  3288. struct x86_exception *exception)
  3289. {
  3290. if (exception)
  3291. exception->error_code = 0;
  3292. return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
  3293. }
  3294. static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3295. {
  3296. /*
  3297. * A nested guest cannot use the MMIO cache if it is using nested
  3298. * page tables, because cr2 is a nGPA while the cache stores GPAs.
  3299. */
  3300. if (mmu_is_nested(vcpu))
  3301. return false;
  3302. if (direct)
  3303. return vcpu_match_mmio_gpa(vcpu, addr);
  3304. return vcpu_match_mmio_gva(vcpu, addr);
  3305. }
  3306. /*
  3307. * Return the level of the lowest level SPTE added to sptes.
  3308. * That SPTE may be non-present.
  3309. *
  3310. * Must be called between walk_shadow_page_lockless_{begin,end}.
  3311. */
  3312. static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
  3313. {
  3314. struct kvm_shadow_walk_iterator iterator;
  3315. int leaf = -1;
  3316. u64 spte;
  3317. for (shadow_walk_init(&iterator, vcpu, addr),
  3318. *root_level = iterator.level;
  3319. shadow_walk_okay(&iterator);
  3320. __shadow_walk_next(&iterator, spte)) {
  3321. leaf = iterator.level;
  3322. spte = mmu_spte_get_lockless(iterator.sptep);
  3323. sptes[leaf] = spte;
  3324. }
  3325. return leaf;
  3326. }
  3327. /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
  3328. static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
  3329. {
  3330. u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
  3331. struct rsvd_bits_validate *rsvd_check;
  3332. int root, leaf, level;
  3333. bool reserved = false;
  3334. walk_shadow_page_lockless_begin(vcpu);
  3335. if (is_tdp_mmu(vcpu->arch.mmu))
  3336. leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
  3337. else
  3338. leaf = get_walk(vcpu, addr, sptes, &root);
  3339. walk_shadow_page_lockless_end(vcpu);
  3340. if (unlikely(leaf < 0)) {
  3341. *sptep = 0ull;
  3342. return reserved;
  3343. }
  3344. *sptep = sptes[leaf];
  3345. /*
  3346. * Skip reserved bits checks on the terminal leaf if it's not a valid
  3347. * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
  3348. * design, always have reserved bits set. The purpose of the checks is
  3349. * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
  3350. */
  3351. if (!is_shadow_present_pte(sptes[leaf]))
  3352. leaf++;
  3353. rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
  3354. for (level = root; level >= leaf; level--)
  3355. reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
  3356. if (reserved) {
  3357. pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
  3358. __func__, addr);
  3359. for (level = root; level >= leaf; level--)
  3360. pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
  3361. sptes[level], level,
  3362. get_rsvd_bits(rsvd_check, sptes[level], level));
  3363. }
  3364. return reserved;
  3365. }
  3366. static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3367. {
  3368. u64 spte;
  3369. bool reserved;
  3370. if (mmio_info_in_cache(vcpu, addr, direct))
  3371. return RET_PF_EMULATE;
  3372. reserved = get_mmio_spte(vcpu, addr, &spte);
  3373. if (WARN_ON(reserved))
  3374. return -EINVAL;
  3375. if (is_mmio_spte(spte)) {
  3376. gfn_t gfn = get_mmio_spte_gfn(spte);
  3377. unsigned int access = get_mmio_spte_access(spte);
  3378. if (!check_mmio_spte(vcpu, spte))
  3379. return RET_PF_INVALID;
  3380. if (direct)
  3381. addr = 0;
  3382. trace_handle_mmio_page_fault(addr, gfn, access);
  3383. vcpu_cache_mmio_info(vcpu, addr, gfn, access);
  3384. return RET_PF_EMULATE;
  3385. }
  3386. /*
  3387. * If the page table is zapped by other cpus, let CPU fault again on
  3388. * the address.
  3389. */
  3390. return RET_PF_RETRY;
  3391. }
  3392. static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
  3393. struct kvm_page_fault *fault)
  3394. {
  3395. if (unlikely(fault->rsvd))
  3396. return false;
  3397. if (!fault->present || !fault->write)
  3398. return false;
  3399. /*
  3400. * guest is writing the page which is write tracked which can
  3401. * not be fixed by page fault handler.
  3402. */
  3403. if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
  3404. return true;
  3405. return false;
  3406. }
  3407. static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
  3408. {
  3409. struct kvm_shadow_walk_iterator iterator;
  3410. u64 spte;
  3411. walk_shadow_page_lockless_begin(vcpu);
  3412. for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
  3413. clear_sp_write_flooding_count(iterator.sptep);
  3414. walk_shadow_page_lockless_end(vcpu);
  3415. }
  3416. static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
  3417. {
  3418. /* make sure the token value is not 0 */
  3419. u32 id = vcpu->arch.apf.id;
  3420. if (id << 12 == 0)
  3421. vcpu->arch.apf.id = 1;
  3422. return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
  3423. }
  3424. static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
  3425. gfn_t gfn)
  3426. {
  3427. struct kvm_arch_async_pf arch;
  3428. arch.token = alloc_apf_token(vcpu);
  3429. arch.gfn = gfn;
  3430. arch.direct_map = vcpu->arch.mmu->root_role.direct;
  3431. arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
  3432. return kvm_setup_async_pf(vcpu, cr2_or_gpa,
  3433. kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
  3434. }
  3435. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  3436. {
  3437. int r;
  3438. if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
  3439. work->wakeup_all)
  3440. return;
  3441. r = kvm_mmu_reload(vcpu);
  3442. if (unlikely(r))
  3443. return;
  3444. if (!vcpu->arch.mmu->root_role.direct &&
  3445. work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
  3446. return;
  3447. kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
  3448. }
  3449. static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  3450. {
  3451. struct kvm_memory_slot *slot = fault->slot;
  3452. bool async;
  3453. /*
  3454. * Retry the page fault if the gfn hit a memslot that is being deleted
  3455. * or moved. This ensures any existing SPTEs for the old memslot will
  3456. * be zapped before KVM inserts a new MMIO SPTE for the gfn.
  3457. */
  3458. if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
  3459. return RET_PF_RETRY;
  3460. if (!kvm_is_visible_memslot(slot)) {
  3461. /* Don't expose private memslots to L2. */
  3462. if (is_guest_mode(vcpu)) {
  3463. fault->slot = NULL;
  3464. fault->pfn = KVM_PFN_NOSLOT;
  3465. fault->map_writable = false;
  3466. return RET_PF_CONTINUE;
  3467. }
  3468. /*
  3469. * If the APIC access page exists but is disabled, go directly
  3470. * to emulation without caching the MMIO access or creating a
  3471. * MMIO SPTE. That way the cache doesn't need to be purged
  3472. * when the AVIC is re-enabled.
  3473. */
  3474. if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
  3475. !kvm_apicv_activated(vcpu->kvm))
  3476. return RET_PF_EMULATE;
  3477. }
  3478. async = false;
  3479. fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, &async,
  3480. fault->write, &fault->map_writable,
  3481. &fault->hva);
  3482. if (!async)
  3483. return RET_PF_CONTINUE; /* *pfn has correct page already */
  3484. if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
  3485. trace_kvm_try_async_get_page(fault->addr, fault->gfn);
  3486. if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
  3487. trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
  3488. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  3489. return RET_PF_RETRY;
  3490. } else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
  3491. return RET_PF_RETRY;
  3492. }
  3493. }
  3494. fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, NULL,
  3495. fault->write, &fault->map_writable,
  3496. &fault->hva);
  3497. return RET_PF_CONTINUE;
  3498. }
  3499. /*
  3500. * Returns true if the page fault is stale and needs to be retried, i.e. if the
  3501. * root was invalidated by a memslot update or a relevant mmu_notifier fired.
  3502. */
  3503. static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
  3504. struct kvm_page_fault *fault,
  3505. unsigned long mmu_seq)
  3506. {
  3507. struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
  3508. /* Special roots, e.g. pae_root, are not backed by shadow pages. */
  3509. if (sp && is_obsolete_sp(vcpu->kvm, sp))
  3510. return true;
  3511. /*
  3512. * Roots without an associated shadow page are considered invalid if
  3513. * there is a pending request to free obsolete roots. The request is
  3514. * only a hint that the current root _may_ be obsolete and needs to be
  3515. * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
  3516. * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
  3517. * to reload even if no vCPU is actively using the root.
  3518. */
  3519. if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
  3520. return true;
  3521. return fault->slot &&
  3522. mmu_invalidate_retry_hva(vcpu->kvm, mmu_seq, fault->hva);
  3523. }
  3524. static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  3525. {
  3526. bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
  3527. unsigned long mmu_seq;
  3528. int r;
  3529. fault->gfn = fault->addr >> PAGE_SHIFT;
  3530. fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
  3531. if (page_fault_handle_page_track(vcpu, fault))
  3532. return RET_PF_EMULATE;
  3533. r = fast_page_fault(vcpu, fault);
  3534. if (r != RET_PF_INVALID)
  3535. return r;
  3536. r = mmu_topup_memory_caches(vcpu, false);
  3537. if (r)
  3538. return r;
  3539. mmu_seq = vcpu->kvm->mmu_invalidate_seq;
  3540. smp_rmb();
  3541. r = kvm_faultin_pfn(vcpu, fault);
  3542. if (r != RET_PF_CONTINUE)
  3543. return r;
  3544. r = handle_abnormal_pfn(vcpu, fault, ACC_ALL);
  3545. if (r != RET_PF_CONTINUE)
  3546. return r;
  3547. r = RET_PF_RETRY;
  3548. if (is_tdp_mmu_fault)
  3549. read_lock(&vcpu->kvm->mmu_lock);
  3550. else
  3551. write_lock(&vcpu->kvm->mmu_lock);
  3552. if (is_page_fault_stale(vcpu, fault, mmu_seq))
  3553. goto out_unlock;
  3554. if (is_tdp_mmu_fault) {
  3555. r = kvm_tdp_mmu_map(vcpu, fault);
  3556. } else {
  3557. r = make_mmu_pages_available(vcpu);
  3558. if (r)
  3559. goto out_unlock;
  3560. r = __direct_map(vcpu, fault);
  3561. }
  3562. out_unlock:
  3563. if (is_tdp_mmu_fault)
  3564. read_unlock(&vcpu->kvm->mmu_lock);
  3565. else
  3566. write_unlock(&vcpu->kvm->mmu_lock);
  3567. kvm_release_pfn_clean(fault->pfn);
  3568. return r;
  3569. }
  3570. static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
  3571. struct kvm_page_fault *fault)
  3572. {
  3573. pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
  3574. /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
  3575. fault->max_level = PG_LEVEL_2M;
  3576. return direct_page_fault(vcpu, fault);
  3577. }
  3578. int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
  3579. u64 fault_address, char *insn, int insn_len)
  3580. {
  3581. int r = 1;
  3582. u32 flags = vcpu->arch.apf.host_apf_flags;
  3583. #ifndef CONFIG_X86_64
  3584. /* A 64-bit CR2 should be impossible on 32-bit KVM. */
  3585. if (WARN_ON_ONCE(fault_address >> 32))
  3586. return -EFAULT;
  3587. #endif
  3588. vcpu->arch.l1tf_flush_l1d = true;
  3589. if (!flags) {
  3590. trace_kvm_page_fault(vcpu, fault_address, error_code);
  3591. if (kvm_event_needs_reinjection(vcpu))
  3592. kvm_mmu_unprotect_page_virt(vcpu, fault_address);
  3593. r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
  3594. insn_len);
  3595. } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
  3596. vcpu->arch.apf.host_apf_flags = 0;
  3597. local_irq_disable();
  3598. kvm_async_pf_task_wait_schedule(fault_address);
  3599. local_irq_enable();
  3600. } else {
  3601. WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
  3602. }
  3603. return r;
  3604. }
  3605. EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
  3606. int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
  3607. {
  3608. /*
  3609. * If the guest's MTRRs may be used to compute the "real" memtype,
  3610. * restrict the mapping level to ensure KVM uses a consistent memtype
  3611. * across the entire mapping. If the host MTRRs are ignored by TDP
  3612. * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
  3613. * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
  3614. * from the guest's MTRRs so that guest accesses to memory that is
  3615. * DMA'd aren't cached against the guest's wishes.
  3616. *
  3617. * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
  3618. * e.g. KVM will force UC memtype for host MMIO.
  3619. */
  3620. if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
  3621. for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
  3622. int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
  3623. gfn_t base = (fault->addr >> PAGE_SHIFT) & ~(page_num - 1);
  3624. if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
  3625. break;
  3626. }
  3627. }
  3628. return direct_page_fault(vcpu, fault);
  3629. }
  3630. static void nonpaging_init_context(struct kvm_mmu *context)
  3631. {
  3632. context->page_fault = nonpaging_page_fault;
  3633. context->gva_to_gpa = nonpaging_gva_to_gpa;
  3634. context->sync_page = nonpaging_sync_page;
  3635. context->invlpg = NULL;
  3636. }
  3637. static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
  3638. union kvm_mmu_page_role role)
  3639. {
  3640. return (role.direct || pgd == root->pgd) &&
  3641. VALID_PAGE(root->hpa) &&
  3642. role.word == to_shadow_page(root->hpa)->role.word;
  3643. }
  3644. /*
  3645. * Find out if a previously cached root matching the new pgd/role is available,
  3646. * and insert the current root as the MRU in the cache.
  3647. * If a matching root is found, it is assigned to kvm_mmu->root and
  3648. * true is returned.
  3649. * If no match is found, kvm_mmu->root is left invalid, the LRU root is
  3650. * evicted to make room for the current root, and false is returned.
  3651. */
  3652. static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
  3653. gpa_t new_pgd,
  3654. union kvm_mmu_page_role new_role)
  3655. {
  3656. uint i;
  3657. if (is_root_usable(&mmu->root, new_pgd, new_role))
  3658. return true;
  3659. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  3660. /*
  3661. * The swaps end up rotating the cache like this:
  3662. * C 0 1 2 3 (on entry to the function)
  3663. * 0 C 1 2 3
  3664. * 1 C 0 2 3
  3665. * 2 C 0 1 3
  3666. * 3 C 0 1 2 (on exit from the loop)
  3667. */
  3668. swap(mmu->root, mmu->prev_roots[i]);
  3669. if (is_root_usable(&mmu->root, new_pgd, new_role))
  3670. return true;
  3671. }
  3672. kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
  3673. return false;
  3674. }
  3675. /*
  3676. * Find out if a previously cached root matching the new pgd/role is available.
  3677. * On entry, mmu->root is invalid.
  3678. * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
  3679. * of the cache becomes invalid, and true is returned.
  3680. * If no match is found, kvm_mmu->root is left invalid and false is returned.
  3681. */
  3682. static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
  3683. gpa_t new_pgd,
  3684. union kvm_mmu_page_role new_role)
  3685. {
  3686. uint i;
  3687. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  3688. if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
  3689. goto hit;
  3690. return false;
  3691. hit:
  3692. swap(mmu->root, mmu->prev_roots[i]);
  3693. /* Bubble up the remaining roots. */
  3694. for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
  3695. mmu->prev_roots[i] = mmu->prev_roots[i + 1];
  3696. mmu->prev_roots[i].hpa = INVALID_PAGE;
  3697. return true;
  3698. }
  3699. static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
  3700. gpa_t new_pgd, union kvm_mmu_page_role new_role)
  3701. {
  3702. /*
  3703. * For now, limit the caching to 64-bit hosts+VMs in order to avoid
  3704. * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
  3705. * later if necessary.
  3706. */
  3707. if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
  3708. kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
  3709. if (VALID_PAGE(mmu->root.hpa))
  3710. return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
  3711. else
  3712. return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
  3713. }
  3714. void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
  3715. {
  3716. struct kvm_mmu *mmu = vcpu->arch.mmu;
  3717. union kvm_mmu_page_role new_role = mmu->root_role;
  3718. if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role)) {
  3719. /* kvm_mmu_ensure_valid_pgd will set up a new root. */
  3720. return;
  3721. }
  3722. /*
  3723. * It's possible that the cached previous root page is obsolete because
  3724. * of a change in the MMU generation number. However, changing the
  3725. * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
  3726. * which will free the root set here and allocate a new one.
  3727. */
  3728. kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
  3729. if (force_flush_and_sync_on_reuse) {
  3730. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  3731. kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
  3732. }
  3733. /*
  3734. * The last MMIO access's GVA and GPA are cached in the VCPU. When
  3735. * switching to a new CR3, that GVA->GPA mapping may no longer be
  3736. * valid. So clear any cached MMIO info even when we don't need to sync
  3737. * the shadow page tables.
  3738. */
  3739. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  3740. /*
  3741. * If this is a direct root page, it doesn't have a write flooding
  3742. * count. Otherwise, clear the write flooding count.
  3743. */
  3744. if (!new_role.direct)
  3745. __clear_sp_write_flooding_count(
  3746. to_shadow_page(vcpu->arch.mmu->root.hpa));
  3747. }
  3748. EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
  3749. static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
  3750. unsigned int access)
  3751. {
  3752. if (unlikely(is_mmio_spte(*sptep))) {
  3753. if (gfn != get_mmio_spte_gfn(*sptep)) {
  3754. mmu_spte_clear_no_track(sptep);
  3755. return true;
  3756. }
  3757. mark_mmio_spte(vcpu, sptep, gfn, access);
  3758. return true;
  3759. }
  3760. return false;
  3761. }
  3762. #define PTTYPE_EPT 18 /* arbitrary */
  3763. #define PTTYPE PTTYPE_EPT
  3764. #include "paging_tmpl.h"
  3765. #undef PTTYPE
  3766. #define PTTYPE 64
  3767. #include "paging_tmpl.h"
  3768. #undef PTTYPE
  3769. #define PTTYPE 32
  3770. #include "paging_tmpl.h"
  3771. #undef PTTYPE
  3772. static void
  3773. __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
  3774. u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
  3775. bool pse, bool amd)
  3776. {
  3777. u64 gbpages_bit_rsvd = 0;
  3778. u64 nonleaf_bit8_rsvd = 0;
  3779. u64 high_bits_rsvd;
  3780. rsvd_check->bad_mt_xwr = 0;
  3781. if (!gbpages)
  3782. gbpages_bit_rsvd = rsvd_bits(7, 7);
  3783. if (level == PT32E_ROOT_LEVEL)
  3784. high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
  3785. else
  3786. high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
  3787. /* Note, NX doesn't exist in PDPTEs, this is handled below. */
  3788. if (!nx)
  3789. high_bits_rsvd |= rsvd_bits(63, 63);
  3790. /*
  3791. * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
  3792. * leaf entries) on AMD CPUs only.
  3793. */
  3794. if (amd)
  3795. nonleaf_bit8_rsvd = rsvd_bits(8, 8);
  3796. switch (level) {
  3797. case PT32_ROOT_LEVEL:
  3798. /* no rsvd bits for 2 level 4K page table entries */
  3799. rsvd_check->rsvd_bits_mask[0][1] = 0;
  3800. rsvd_check->rsvd_bits_mask[0][0] = 0;
  3801. rsvd_check->rsvd_bits_mask[1][0] =
  3802. rsvd_check->rsvd_bits_mask[0][0];
  3803. if (!pse) {
  3804. rsvd_check->rsvd_bits_mask[1][1] = 0;
  3805. break;
  3806. }
  3807. if (is_cpuid_PSE36())
  3808. /* 36bits PSE 4MB page */
  3809. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
  3810. else
  3811. /* 32 bits PSE 4MB page */
  3812. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
  3813. break;
  3814. case PT32E_ROOT_LEVEL:
  3815. rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
  3816. high_bits_rsvd |
  3817. rsvd_bits(5, 8) |
  3818. rsvd_bits(1, 2); /* PDPTE */
  3819. rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
  3820. rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
  3821. rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
  3822. rsvd_bits(13, 20); /* large page */
  3823. rsvd_check->rsvd_bits_mask[1][0] =
  3824. rsvd_check->rsvd_bits_mask[0][0];
  3825. break;
  3826. case PT64_ROOT_5LEVEL:
  3827. rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
  3828. nonleaf_bit8_rsvd |
  3829. rsvd_bits(7, 7);
  3830. rsvd_check->rsvd_bits_mask[1][4] =
  3831. rsvd_check->rsvd_bits_mask[0][4];
  3832. fallthrough;
  3833. case PT64_ROOT_4LEVEL:
  3834. rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
  3835. nonleaf_bit8_rsvd |
  3836. rsvd_bits(7, 7);
  3837. rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
  3838. gbpages_bit_rsvd;
  3839. rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
  3840. rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
  3841. rsvd_check->rsvd_bits_mask[1][3] =
  3842. rsvd_check->rsvd_bits_mask[0][3];
  3843. rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
  3844. gbpages_bit_rsvd |
  3845. rsvd_bits(13, 29);
  3846. rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
  3847. rsvd_bits(13, 20); /* large page */
  3848. rsvd_check->rsvd_bits_mask[1][0] =
  3849. rsvd_check->rsvd_bits_mask[0][0];
  3850. break;
  3851. }
  3852. }
  3853. static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
  3854. {
  3855. /*
  3856. * If TDP is enabled, let the guest use GBPAGES if they're supported in
  3857. * hardware. The hardware page walker doesn't let KVM disable GBPAGES,
  3858. * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
  3859. * walk for performance and complexity reasons. Not to mention KVM
  3860. * _can't_ solve the problem because GVA->GPA walks aren't visible to
  3861. * KVM once a TDP translation is installed. Mimic hardware behavior so
  3862. * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
  3863. */
  3864. return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
  3865. guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
  3866. }
  3867. static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
  3868. struct kvm_mmu *context)
  3869. {
  3870. __reset_rsvds_bits_mask(&context->guest_rsvd_check,
  3871. vcpu->arch.reserved_gpa_bits,
  3872. context->cpu_role.base.level, is_efer_nx(context),
  3873. guest_can_use_gbpages(vcpu),
  3874. is_cr4_pse(context),
  3875. guest_cpuid_is_amd_or_hygon(vcpu));
  3876. }
  3877. static void
  3878. __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
  3879. u64 pa_bits_rsvd, bool execonly, int huge_page_level)
  3880. {
  3881. u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
  3882. u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
  3883. u64 bad_mt_xwr;
  3884. if (huge_page_level < PG_LEVEL_1G)
  3885. large_1g_rsvd = rsvd_bits(7, 7);
  3886. if (huge_page_level < PG_LEVEL_2M)
  3887. large_2m_rsvd = rsvd_bits(7, 7);
  3888. rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
  3889. rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
  3890. rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
  3891. rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
  3892. rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
  3893. /* large page */
  3894. rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
  3895. rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
  3896. rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
  3897. rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
  3898. rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
  3899. bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
  3900. bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
  3901. bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
  3902. bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
  3903. bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
  3904. if (!execonly) {
  3905. /* bits 0..2 must not be 100 unless VMX capabilities allow it */
  3906. bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
  3907. }
  3908. rsvd_check->bad_mt_xwr = bad_mt_xwr;
  3909. }
  3910. static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
  3911. struct kvm_mmu *context, bool execonly, int huge_page_level)
  3912. {
  3913. __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
  3914. vcpu->arch.reserved_gpa_bits, execonly,
  3915. huge_page_level);
  3916. }
  3917. static inline u64 reserved_hpa_bits(void)
  3918. {
  3919. return rsvd_bits(shadow_phys_bits, 63);
  3920. }
  3921. /*
  3922. * the page table on host is the shadow page table for the page
  3923. * table in guest or amd nested guest, its mmu features completely
  3924. * follow the features in guest.
  3925. */
  3926. static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
  3927. struct kvm_mmu *context)
  3928. {
  3929. /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
  3930. bool is_amd = true;
  3931. /* KVM doesn't use 2-level page tables for the shadow MMU. */
  3932. bool is_pse = false;
  3933. struct rsvd_bits_validate *shadow_zero_check;
  3934. int i;
  3935. WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
  3936. shadow_zero_check = &context->shadow_zero_check;
  3937. __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
  3938. context->root_role.level,
  3939. context->root_role.efer_nx,
  3940. guest_can_use_gbpages(vcpu), is_pse, is_amd);
  3941. if (!shadow_me_mask)
  3942. return;
  3943. for (i = context->root_role.level; --i >= 0;) {
  3944. /*
  3945. * So far shadow_me_value is a constant during KVM's life
  3946. * time. Bits in shadow_me_value are allowed to be set.
  3947. * Bits in shadow_me_mask but not in shadow_me_value are
  3948. * not allowed to be set.
  3949. */
  3950. shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
  3951. shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
  3952. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
  3953. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
  3954. }
  3955. }
  3956. static inline bool boot_cpu_is_amd(void)
  3957. {
  3958. WARN_ON_ONCE(!tdp_enabled);
  3959. return shadow_x_mask == 0;
  3960. }
  3961. /*
  3962. * the direct page table on host, use as much mmu features as
  3963. * possible, however, kvm currently does not do execution-protection.
  3964. */
  3965. static void
  3966. reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
  3967. {
  3968. struct rsvd_bits_validate *shadow_zero_check;
  3969. int i;
  3970. shadow_zero_check = &context->shadow_zero_check;
  3971. if (boot_cpu_is_amd())
  3972. __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
  3973. context->root_role.level, true,
  3974. boot_cpu_has(X86_FEATURE_GBPAGES),
  3975. false, true);
  3976. else
  3977. __reset_rsvds_bits_mask_ept(shadow_zero_check,
  3978. reserved_hpa_bits(), false,
  3979. max_huge_page_level);
  3980. if (!shadow_me_mask)
  3981. return;
  3982. for (i = context->root_role.level; --i >= 0;) {
  3983. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
  3984. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
  3985. }
  3986. }
  3987. /*
  3988. * as the comments in reset_shadow_zero_bits_mask() except it
  3989. * is the shadow page table for intel nested guest.
  3990. */
  3991. static void
  3992. reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
  3993. {
  3994. __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
  3995. reserved_hpa_bits(), execonly,
  3996. max_huge_page_level);
  3997. }
  3998. #define BYTE_MASK(access) \
  3999. ((1 & (access) ? 2 : 0) | \
  4000. (2 & (access) ? 4 : 0) | \
  4001. (3 & (access) ? 8 : 0) | \
  4002. (4 & (access) ? 16 : 0) | \
  4003. (5 & (access) ? 32 : 0) | \
  4004. (6 & (access) ? 64 : 0) | \
  4005. (7 & (access) ? 128 : 0))
  4006. static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
  4007. {
  4008. unsigned byte;
  4009. const u8 x = BYTE_MASK(ACC_EXEC_MASK);
  4010. const u8 w = BYTE_MASK(ACC_WRITE_MASK);
  4011. const u8 u = BYTE_MASK(ACC_USER_MASK);
  4012. bool cr4_smep = is_cr4_smep(mmu);
  4013. bool cr4_smap = is_cr4_smap(mmu);
  4014. bool cr0_wp = is_cr0_wp(mmu);
  4015. bool efer_nx = is_efer_nx(mmu);
  4016. for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
  4017. unsigned pfec = byte << 1;
  4018. /*
  4019. * Each "*f" variable has a 1 bit for each UWX value
  4020. * that causes a fault with the given PFEC.
  4021. */
  4022. /* Faults from writes to non-writable pages */
  4023. u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
  4024. /* Faults from user mode accesses to supervisor pages */
  4025. u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
  4026. /* Faults from fetches of non-executable pages*/
  4027. u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
  4028. /* Faults from kernel mode fetches of user pages */
  4029. u8 smepf = 0;
  4030. /* Faults from kernel mode accesses of user pages */
  4031. u8 smapf = 0;
  4032. if (!ept) {
  4033. /* Faults from kernel mode accesses to user pages */
  4034. u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
  4035. /* Not really needed: !nx will cause pte.nx to fault */
  4036. if (!efer_nx)
  4037. ff = 0;
  4038. /* Allow supervisor writes if !cr0.wp */
  4039. if (!cr0_wp)
  4040. wf = (pfec & PFERR_USER_MASK) ? wf : 0;
  4041. /* Disallow supervisor fetches of user code if cr4.smep */
  4042. if (cr4_smep)
  4043. smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
  4044. /*
  4045. * SMAP:kernel-mode data accesses from user-mode
  4046. * mappings should fault. A fault is considered
  4047. * as a SMAP violation if all of the following
  4048. * conditions are true:
  4049. * - X86_CR4_SMAP is set in CR4
  4050. * - A user page is accessed
  4051. * - The access is not a fetch
  4052. * - The access is supervisor mode
  4053. * - If implicit supervisor access or X86_EFLAGS_AC is clear
  4054. *
  4055. * Here, we cover the first four conditions.
  4056. * The fifth is computed dynamically in permission_fault();
  4057. * PFERR_RSVD_MASK bit will be set in PFEC if the access is
  4058. * *not* subject to SMAP restrictions.
  4059. */
  4060. if (cr4_smap)
  4061. smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
  4062. }
  4063. mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
  4064. }
  4065. }
  4066. /*
  4067. * PKU is an additional mechanism by which the paging controls access to
  4068. * user-mode addresses based on the value in the PKRU register. Protection
  4069. * key violations are reported through a bit in the page fault error code.
  4070. * Unlike other bits of the error code, the PK bit is not known at the
  4071. * call site of e.g. gva_to_gpa; it must be computed directly in
  4072. * permission_fault based on two bits of PKRU, on some machine state (CR4,
  4073. * CR0, EFER, CPL), and on other bits of the error code and the page tables.
  4074. *
  4075. * In particular the following conditions come from the error code, the
  4076. * page tables and the machine state:
  4077. * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
  4078. * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
  4079. * - PK is always zero if U=0 in the page tables
  4080. * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
  4081. *
  4082. * The PKRU bitmask caches the result of these four conditions. The error
  4083. * code (minus the P bit) and the page table's U bit form an index into the
  4084. * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
  4085. * with the two bits of the PKRU register corresponding to the protection key.
  4086. * For the first three conditions above the bits will be 00, thus masking
  4087. * away both AD and WD. For all reads or if the last condition holds, WD
  4088. * only will be masked away.
  4089. */
  4090. static void update_pkru_bitmask(struct kvm_mmu *mmu)
  4091. {
  4092. unsigned bit;
  4093. bool wp;
  4094. mmu->pkru_mask = 0;
  4095. if (!is_cr4_pke(mmu))
  4096. return;
  4097. wp = is_cr0_wp(mmu);
  4098. for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
  4099. unsigned pfec, pkey_bits;
  4100. bool check_pkey, check_write, ff, uf, wf, pte_user;
  4101. pfec = bit << 1;
  4102. ff = pfec & PFERR_FETCH_MASK;
  4103. uf = pfec & PFERR_USER_MASK;
  4104. wf = pfec & PFERR_WRITE_MASK;
  4105. /* PFEC.RSVD is replaced by ACC_USER_MASK. */
  4106. pte_user = pfec & PFERR_RSVD_MASK;
  4107. /*
  4108. * Only need to check the access which is not an
  4109. * instruction fetch and is to a user page.
  4110. */
  4111. check_pkey = (!ff && pte_user);
  4112. /*
  4113. * write access is controlled by PKRU if it is a
  4114. * user access or CR0.WP = 1.
  4115. */
  4116. check_write = check_pkey && wf && (uf || wp);
  4117. /* PKRU.AD stops both read and write access. */
  4118. pkey_bits = !!check_pkey;
  4119. /* PKRU.WD stops write access. */
  4120. pkey_bits |= (!!check_write) << 1;
  4121. mmu->pkru_mask |= (pkey_bits & 3) << pfec;
  4122. }
  4123. }
  4124. static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
  4125. struct kvm_mmu *mmu)
  4126. {
  4127. if (!is_cr0_pg(mmu))
  4128. return;
  4129. reset_guest_rsvds_bits_mask(vcpu, mmu);
  4130. update_permission_bitmask(mmu, false);
  4131. update_pkru_bitmask(mmu);
  4132. }
  4133. static void paging64_init_context(struct kvm_mmu *context)
  4134. {
  4135. context->page_fault = paging64_page_fault;
  4136. context->gva_to_gpa = paging64_gva_to_gpa;
  4137. context->sync_page = paging64_sync_page;
  4138. context->invlpg = paging64_invlpg;
  4139. }
  4140. static void paging32_init_context(struct kvm_mmu *context)
  4141. {
  4142. context->page_fault = paging32_page_fault;
  4143. context->gva_to_gpa = paging32_gva_to_gpa;
  4144. context->sync_page = paging32_sync_page;
  4145. context->invlpg = paging32_invlpg;
  4146. }
  4147. static union kvm_cpu_role
  4148. kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
  4149. {
  4150. union kvm_cpu_role role = {0};
  4151. role.base.access = ACC_ALL;
  4152. role.base.smm = is_smm(vcpu);
  4153. role.base.guest_mode = is_guest_mode(vcpu);
  4154. role.ext.valid = 1;
  4155. if (!____is_cr0_pg(regs)) {
  4156. role.base.direct = 1;
  4157. return role;
  4158. }
  4159. role.base.efer_nx = ____is_efer_nx(regs);
  4160. role.base.cr0_wp = ____is_cr0_wp(regs);
  4161. role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
  4162. role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
  4163. role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
  4164. if (____is_efer_lma(regs))
  4165. role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
  4166. : PT64_ROOT_4LEVEL;
  4167. else if (____is_cr4_pae(regs))
  4168. role.base.level = PT32E_ROOT_LEVEL;
  4169. else
  4170. role.base.level = PT32_ROOT_LEVEL;
  4171. role.ext.cr4_smep = ____is_cr4_smep(regs);
  4172. role.ext.cr4_smap = ____is_cr4_smap(regs);
  4173. role.ext.cr4_pse = ____is_cr4_pse(regs);
  4174. /* PKEY and LA57 are active iff long mode is active. */
  4175. role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
  4176. role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
  4177. role.ext.efer_lma = ____is_efer_lma(regs);
  4178. return role;
  4179. }
  4180. void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
  4181. struct kvm_mmu *mmu)
  4182. {
  4183. const bool cr0_wp = !!kvm_read_cr0_bits(vcpu, X86_CR0_WP);
  4184. BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
  4185. BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
  4186. if (is_cr0_wp(mmu) == cr0_wp)
  4187. return;
  4188. mmu->cpu_role.base.cr0_wp = cr0_wp;
  4189. reset_guest_paging_metadata(vcpu, mmu);
  4190. }
  4191. static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
  4192. {
  4193. /* tdp_root_level is architecture forced level, use it if nonzero */
  4194. if (tdp_root_level)
  4195. return tdp_root_level;
  4196. /* Use 5-level TDP if and only if it's useful/necessary. */
  4197. if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
  4198. return 4;
  4199. return max_tdp_level;
  4200. }
  4201. static union kvm_mmu_page_role
  4202. kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
  4203. union kvm_cpu_role cpu_role)
  4204. {
  4205. union kvm_mmu_page_role role = {0};
  4206. role.access = ACC_ALL;
  4207. role.cr0_wp = true;
  4208. role.efer_nx = true;
  4209. role.smm = cpu_role.base.smm;
  4210. role.guest_mode = cpu_role.base.guest_mode;
  4211. role.ad_disabled = !kvm_ad_enabled();
  4212. role.level = kvm_mmu_get_tdp_level(vcpu);
  4213. role.direct = true;
  4214. role.has_4_byte_gpte = false;
  4215. return role;
  4216. }
  4217. static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
  4218. union kvm_cpu_role cpu_role)
  4219. {
  4220. struct kvm_mmu *context = &vcpu->arch.root_mmu;
  4221. union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
  4222. if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
  4223. root_role.word == context->root_role.word)
  4224. return;
  4225. context->cpu_role.as_u64 = cpu_role.as_u64;
  4226. context->root_role.word = root_role.word;
  4227. context->page_fault = kvm_tdp_page_fault;
  4228. context->sync_page = nonpaging_sync_page;
  4229. context->invlpg = NULL;
  4230. context->get_guest_pgd = get_guest_cr3;
  4231. context->get_pdptr = kvm_pdptr_read;
  4232. context->inject_page_fault = kvm_inject_page_fault;
  4233. if (!is_cr0_pg(context))
  4234. context->gva_to_gpa = nonpaging_gva_to_gpa;
  4235. else if (is_cr4_pae(context))
  4236. context->gva_to_gpa = paging64_gva_to_gpa;
  4237. else
  4238. context->gva_to_gpa = paging32_gva_to_gpa;
  4239. reset_guest_paging_metadata(vcpu, context);
  4240. reset_tdp_shadow_zero_bits_mask(context);
  4241. }
  4242. static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
  4243. union kvm_cpu_role cpu_role,
  4244. union kvm_mmu_page_role root_role)
  4245. {
  4246. if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
  4247. root_role.word == context->root_role.word)
  4248. return;
  4249. context->cpu_role.as_u64 = cpu_role.as_u64;
  4250. context->root_role.word = root_role.word;
  4251. if (!is_cr0_pg(context))
  4252. nonpaging_init_context(context);
  4253. else if (is_cr4_pae(context))
  4254. paging64_init_context(context);
  4255. else
  4256. paging32_init_context(context);
  4257. reset_guest_paging_metadata(vcpu, context);
  4258. reset_shadow_zero_bits_mask(vcpu, context);
  4259. }
  4260. static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
  4261. union kvm_cpu_role cpu_role)
  4262. {
  4263. struct kvm_mmu *context = &vcpu->arch.root_mmu;
  4264. union kvm_mmu_page_role root_role;
  4265. root_role = cpu_role.base;
  4266. /* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
  4267. root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
  4268. /*
  4269. * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
  4270. * KVM uses NX when TDP is disabled to handle a variety of scenarios,
  4271. * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
  4272. * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
  4273. * The iTLB multi-hit workaround can be toggled at any time, so assume
  4274. * NX can be used by any non-nested shadow MMU to avoid having to reset
  4275. * MMU contexts.
  4276. */
  4277. root_role.efer_nx = true;
  4278. shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
  4279. }
  4280. void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
  4281. unsigned long cr4, u64 efer, gpa_t nested_cr3)
  4282. {
  4283. struct kvm_mmu *context = &vcpu->arch.guest_mmu;
  4284. struct kvm_mmu_role_regs regs = {
  4285. .cr0 = cr0,
  4286. .cr4 = cr4 & ~X86_CR4_PKE,
  4287. .efer = efer,
  4288. };
  4289. union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
  4290. union kvm_mmu_page_role root_role;
  4291. /* NPT requires CR0.PG=1. */
  4292. WARN_ON_ONCE(cpu_role.base.direct);
  4293. root_role = cpu_role.base;
  4294. root_role.level = kvm_mmu_get_tdp_level(vcpu);
  4295. if (root_role.level == PT64_ROOT_5LEVEL &&
  4296. cpu_role.base.level == PT64_ROOT_4LEVEL)
  4297. root_role.passthrough = 1;
  4298. shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
  4299. kvm_mmu_new_pgd(vcpu, nested_cr3);
  4300. }
  4301. EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
  4302. static union kvm_cpu_role
  4303. kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
  4304. bool execonly, u8 level)
  4305. {
  4306. union kvm_cpu_role role = {0};
  4307. /*
  4308. * KVM does not support SMM transfer monitors, and consequently does not
  4309. * support the "entry to SMM" control either. role.base.smm is always 0.
  4310. */
  4311. WARN_ON_ONCE(is_smm(vcpu));
  4312. role.base.level = level;
  4313. role.base.has_4_byte_gpte = false;
  4314. role.base.direct = false;
  4315. role.base.ad_disabled = !accessed_dirty;
  4316. role.base.guest_mode = true;
  4317. role.base.access = ACC_ALL;
  4318. role.ext.word = 0;
  4319. role.ext.execonly = execonly;
  4320. role.ext.valid = 1;
  4321. return role;
  4322. }
  4323. void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
  4324. int huge_page_level, bool accessed_dirty,
  4325. gpa_t new_eptp)
  4326. {
  4327. struct kvm_mmu *context = &vcpu->arch.guest_mmu;
  4328. u8 level = vmx_eptp_page_walk_level(new_eptp);
  4329. union kvm_cpu_role new_mode =
  4330. kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
  4331. execonly, level);
  4332. if (new_mode.as_u64 != context->cpu_role.as_u64) {
  4333. /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
  4334. context->cpu_role.as_u64 = new_mode.as_u64;
  4335. context->root_role.word = new_mode.base.word;
  4336. context->page_fault = ept_page_fault;
  4337. context->gva_to_gpa = ept_gva_to_gpa;
  4338. context->sync_page = ept_sync_page;
  4339. context->invlpg = ept_invlpg;
  4340. update_permission_bitmask(context, true);
  4341. context->pkru_mask = 0;
  4342. reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
  4343. reset_ept_shadow_zero_bits_mask(context, execonly);
  4344. }
  4345. kvm_mmu_new_pgd(vcpu, new_eptp);
  4346. }
  4347. EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
  4348. static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
  4349. union kvm_cpu_role cpu_role)
  4350. {
  4351. struct kvm_mmu *context = &vcpu->arch.root_mmu;
  4352. kvm_init_shadow_mmu(vcpu, cpu_role);
  4353. context->get_guest_pgd = get_guest_cr3;
  4354. context->get_pdptr = kvm_pdptr_read;
  4355. context->inject_page_fault = kvm_inject_page_fault;
  4356. }
  4357. static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
  4358. union kvm_cpu_role new_mode)
  4359. {
  4360. struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
  4361. if (new_mode.as_u64 == g_context->cpu_role.as_u64)
  4362. return;
  4363. g_context->cpu_role.as_u64 = new_mode.as_u64;
  4364. g_context->get_guest_pgd = get_guest_cr3;
  4365. g_context->get_pdptr = kvm_pdptr_read;
  4366. g_context->inject_page_fault = kvm_inject_page_fault;
  4367. /*
  4368. * L2 page tables are never shadowed, so there is no need to sync
  4369. * SPTEs.
  4370. */
  4371. g_context->invlpg = NULL;
  4372. /*
  4373. * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
  4374. * L1's nested page tables (e.g. EPT12). The nested translation
  4375. * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
  4376. * L2's page tables as the first level of translation and L1's
  4377. * nested page tables as the second level of translation. Basically
  4378. * the gva_to_gpa functions between mmu and nested_mmu are swapped.
  4379. */
  4380. if (!is_paging(vcpu))
  4381. g_context->gva_to_gpa = nonpaging_gva_to_gpa;
  4382. else if (is_long_mode(vcpu))
  4383. g_context->gva_to_gpa = paging64_gva_to_gpa;
  4384. else if (is_pae(vcpu))
  4385. g_context->gva_to_gpa = paging64_gva_to_gpa;
  4386. else
  4387. g_context->gva_to_gpa = paging32_gva_to_gpa;
  4388. reset_guest_paging_metadata(vcpu, g_context);
  4389. }
  4390. void kvm_init_mmu(struct kvm_vcpu *vcpu)
  4391. {
  4392. struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
  4393. union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
  4394. if (mmu_is_nested(vcpu))
  4395. init_kvm_nested_mmu(vcpu, cpu_role);
  4396. else if (tdp_enabled)
  4397. init_kvm_tdp_mmu(vcpu, cpu_role);
  4398. else
  4399. init_kvm_softmmu(vcpu, cpu_role);
  4400. }
  4401. EXPORT_SYMBOL_GPL(kvm_init_mmu);
  4402. void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
  4403. {
  4404. /*
  4405. * Invalidate all MMU roles to force them to reinitialize as CPUID
  4406. * information is factored into reserved bit calculations.
  4407. *
  4408. * Correctly handling multiple vCPU models with respect to paging and
  4409. * physical address properties) in a single VM would require tracking
  4410. * all relevant CPUID information in kvm_mmu_page_role. That is very
  4411. * undesirable as it would increase the memory requirements for
  4412. * gfn_track (see struct kvm_mmu_page_role comments). For now that
  4413. * problem is swept under the rug; KVM's CPUID API is horrific and
  4414. * it's all but impossible to solve it without introducing a new API.
  4415. */
  4416. vcpu->arch.root_mmu.root_role.word = 0;
  4417. vcpu->arch.guest_mmu.root_role.word = 0;
  4418. vcpu->arch.nested_mmu.root_role.word = 0;
  4419. vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
  4420. vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
  4421. vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
  4422. kvm_mmu_reset_context(vcpu);
  4423. /*
  4424. * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
  4425. * kvm_arch_vcpu_ioctl().
  4426. */
  4427. KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
  4428. }
  4429. void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
  4430. {
  4431. kvm_mmu_unload(vcpu);
  4432. kvm_init_mmu(vcpu);
  4433. }
  4434. EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
  4435. int kvm_mmu_load(struct kvm_vcpu *vcpu)
  4436. {
  4437. int r;
  4438. r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
  4439. if (r)
  4440. goto out;
  4441. r = mmu_alloc_special_roots(vcpu);
  4442. if (r)
  4443. goto out;
  4444. if (vcpu->arch.mmu->root_role.direct)
  4445. r = mmu_alloc_direct_roots(vcpu);
  4446. else
  4447. r = mmu_alloc_shadow_roots(vcpu);
  4448. if (r)
  4449. goto out;
  4450. kvm_mmu_sync_roots(vcpu);
  4451. kvm_mmu_load_pgd(vcpu);
  4452. /*
  4453. * Flush any TLB entries for the new root, the provenance of the root
  4454. * is unknown. Even if KVM ensures there are no stale TLB entries
  4455. * for a freed root, in theory another hypervisor could have left
  4456. * stale entries. Flushing on alloc also allows KVM to skip the TLB
  4457. * flush when freeing a root (see kvm_tdp_mmu_put_root()).
  4458. */
  4459. static_call(kvm_x86_flush_tlb_current)(vcpu);
  4460. out:
  4461. return r;
  4462. }
  4463. void kvm_mmu_unload(struct kvm_vcpu *vcpu)
  4464. {
  4465. struct kvm *kvm = vcpu->kvm;
  4466. kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
  4467. WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
  4468. kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
  4469. WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
  4470. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  4471. }
  4472. static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
  4473. {
  4474. struct kvm_mmu_page *sp;
  4475. if (!VALID_PAGE(root_hpa))
  4476. return false;
  4477. /*
  4478. * When freeing obsolete roots, treat roots as obsolete if they don't
  4479. * have an associated shadow page. This does mean KVM will get false
  4480. * positives and free roots that don't strictly need to be freed, but
  4481. * such false positives are relatively rare:
  4482. *
  4483. * (a) only PAE paging and nested NPT has roots without shadow pages
  4484. * (b) remote reloads due to a memslot update obsoletes _all_ roots
  4485. * (c) KVM doesn't track previous roots for PAE paging, and the guest
  4486. * is unlikely to zap an in-use PGD.
  4487. */
  4488. sp = to_shadow_page(root_hpa);
  4489. return !sp || is_obsolete_sp(kvm, sp);
  4490. }
  4491. static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
  4492. {
  4493. unsigned long roots_to_free = 0;
  4494. int i;
  4495. if (is_obsolete_root(kvm, mmu->root.hpa))
  4496. roots_to_free |= KVM_MMU_ROOT_CURRENT;
  4497. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  4498. if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
  4499. roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
  4500. }
  4501. if (roots_to_free)
  4502. kvm_mmu_free_roots(kvm, mmu, roots_to_free);
  4503. }
  4504. void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
  4505. {
  4506. __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
  4507. __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
  4508. }
  4509. static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
  4510. int *bytes)
  4511. {
  4512. u64 gentry = 0;
  4513. int r;
  4514. /*
  4515. * Assume that the pte write on a page table of the same type
  4516. * as the current vcpu paging mode since we update the sptes only
  4517. * when they have the same mode.
  4518. */
  4519. if (is_pae(vcpu) && *bytes == 4) {
  4520. /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
  4521. *gpa &= ~(gpa_t)7;
  4522. *bytes = 8;
  4523. }
  4524. if (*bytes == 4 || *bytes == 8) {
  4525. r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
  4526. if (r)
  4527. gentry = 0;
  4528. }
  4529. return gentry;
  4530. }
  4531. /*
  4532. * If we're seeing too many writes to a page, it may no longer be a page table,
  4533. * or we may be forking, in which case it is better to unmap the page.
  4534. */
  4535. static bool detect_write_flooding(struct kvm_mmu_page *sp)
  4536. {
  4537. /*
  4538. * Skip write-flooding detected for the sp whose level is 1, because
  4539. * it can become unsync, then the guest page is not write-protected.
  4540. */
  4541. if (sp->role.level == PG_LEVEL_4K)
  4542. return false;
  4543. atomic_inc(&sp->write_flooding_count);
  4544. return atomic_read(&sp->write_flooding_count) >= 3;
  4545. }
  4546. /*
  4547. * Misaligned accesses are too much trouble to fix up; also, they usually
  4548. * indicate a page is not used as a page table.
  4549. */
  4550. static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
  4551. int bytes)
  4552. {
  4553. unsigned offset, pte_size, misaligned;
  4554. pgprintk("misaligned: gpa %llx bytes %d role %x\n",
  4555. gpa, bytes, sp->role.word);
  4556. offset = offset_in_page(gpa);
  4557. pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
  4558. /*
  4559. * Sometimes, the OS only writes the last one bytes to update status
  4560. * bits, for example, in linux, andb instruction is used in clear_bit().
  4561. */
  4562. if (!(offset & (pte_size - 1)) && bytes == 1)
  4563. return false;
  4564. misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
  4565. misaligned |= bytes < 4;
  4566. return misaligned;
  4567. }
  4568. static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
  4569. {
  4570. unsigned page_offset, quadrant;
  4571. u64 *spte;
  4572. int level;
  4573. page_offset = offset_in_page(gpa);
  4574. level = sp->role.level;
  4575. *nspte = 1;
  4576. if (sp->role.has_4_byte_gpte) {
  4577. page_offset <<= 1; /* 32->64 */
  4578. /*
  4579. * A 32-bit pde maps 4MB while the shadow pdes map
  4580. * only 2MB. So we need to double the offset again
  4581. * and zap two pdes instead of one.
  4582. */
  4583. if (level == PT32_ROOT_LEVEL) {
  4584. page_offset &= ~7; /* kill rounding error */
  4585. page_offset <<= 1;
  4586. *nspte = 2;
  4587. }
  4588. quadrant = page_offset >> PAGE_SHIFT;
  4589. page_offset &= ~PAGE_MASK;
  4590. if (quadrant != sp->role.quadrant)
  4591. return NULL;
  4592. }
  4593. spte = &sp->spt[page_offset / sizeof(*spte)];
  4594. return spte;
  4595. }
  4596. static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
  4597. const u8 *new, int bytes,
  4598. struct kvm_page_track_notifier_node *node)
  4599. {
  4600. gfn_t gfn = gpa >> PAGE_SHIFT;
  4601. struct kvm_mmu_page *sp;
  4602. LIST_HEAD(invalid_list);
  4603. u64 entry, gentry, *spte;
  4604. int npte;
  4605. bool flush = false;
  4606. /*
  4607. * If we don't have indirect shadow pages, it means no page is
  4608. * write-protected, so we can exit simply.
  4609. */
  4610. if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
  4611. return;
  4612. pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
  4613. write_lock(&vcpu->kvm->mmu_lock);
  4614. gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
  4615. ++vcpu->kvm->stat.mmu_pte_write;
  4616. for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
  4617. if (detect_write_misaligned(sp, gpa, bytes) ||
  4618. detect_write_flooding(sp)) {
  4619. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
  4620. ++vcpu->kvm->stat.mmu_flooded;
  4621. continue;
  4622. }
  4623. spte = get_written_sptes(sp, gpa, &npte);
  4624. if (!spte)
  4625. continue;
  4626. while (npte--) {
  4627. entry = *spte;
  4628. mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
  4629. if (gentry && sp->role.level != PG_LEVEL_4K)
  4630. ++vcpu->kvm->stat.mmu_pde_zapped;
  4631. if (is_shadow_present_pte(entry))
  4632. flush = true;
  4633. ++spte;
  4634. }
  4635. }
  4636. kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
  4637. write_unlock(&vcpu->kvm->mmu_lock);
  4638. }
  4639. int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
  4640. void *insn, int insn_len)
  4641. {
  4642. int r, emulation_type = EMULTYPE_PF;
  4643. bool direct = vcpu->arch.mmu->root_role.direct;
  4644. if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
  4645. return RET_PF_RETRY;
  4646. r = RET_PF_INVALID;
  4647. if (unlikely(error_code & PFERR_RSVD_MASK)) {
  4648. r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
  4649. if (r == RET_PF_EMULATE)
  4650. goto emulate;
  4651. }
  4652. if (r == RET_PF_INVALID) {
  4653. r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
  4654. lower_32_bits(error_code), false);
  4655. if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
  4656. return -EIO;
  4657. }
  4658. if (r < 0)
  4659. return r;
  4660. if (r != RET_PF_EMULATE)
  4661. return 1;
  4662. /*
  4663. * Before emulating the instruction, check if the error code
  4664. * was due to a RO violation while translating the guest page.
  4665. * This can occur when using nested virtualization with nested
  4666. * paging in both guests. If true, we simply unprotect the page
  4667. * and resume the guest.
  4668. */
  4669. if (vcpu->arch.mmu->root_role.direct &&
  4670. (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
  4671. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
  4672. return 1;
  4673. }
  4674. /*
  4675. * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
  4676. * optimistically try to just unprotect the page and let the processor
  4677. * re-execute the instruction that caused the page fault. Do not allow
  4678. * retrying MMIO emulation, as it's not only pointless but could also
  4679. * cause us to enter an infinite loop because the processor will keep
  4680. * faulting on the non-existent MMIO address. Retrying an instruction
  4681. * from a nested guest is also pointless and dangerous as we are only
  4682. * explicitly shadowing L1's page tables, i.e. unprotecting something
  4683. * for L1 isn't going to magically fix whatever issue cause L2 to fail.
  4684. */
  4685. if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
  4686. emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
  4687. emulate:
  4688. return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
  4689. insn_len);
  4690. }
  4691. EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
  4692. void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  4693. gva_t gva, hpa_t root_hpa)
  4694. {
  4695. int i;
  4696. /* It's actually a GPA for vcpu->arch.guest_mmu. */
  4697. if (mmu != &vcpu->arch.guest_mmu) {
  4698. /* INVLPG on a non-canonical address is a NOP according to the SDM. */
  4699. if (is_noncanonical_address(gva, vcpu))
  4700. return;
  4701. static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
  4702. }
  4703. if (!mmu->invlpg)
  4704. return;
  4705. if (root_hpa == INVALID_PAGE) {
  4706. mmu->invlpg(vcpu, gva, mmu->root.hpa);
  4707. /*
  4708. * INVLPG is required to invalidate any global mappings for the VA,
  4709. * irrespective of PCID. Since it would take us roughly similar amount
  4710. * of work to determine whether any of the prev_root mappings of the VA
  4711. * is marked global, or to just sync it blindly, so we might as well
  4712. * just always sync it.
  4713. *
  4714. * Mappings not reachable via the current cr3 or the prev_roots will be
  4715. * synced when switching to that cr3, so nothing needs to be done here
  4716. * for them.
  4717. */
  4718. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4719. if (VALID_PAGE(mmu->prev_roots[i].hpa))
  4720. mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
  4721. } else {
  4722. mmu->invlpg(vcpu, gva, root_hpa);
  4723. }
  4724. }
  4725. void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
  4726. {
  4727. kvm_mmu_invalidate_gva(vcpu, vcpu->arch.walk_mmu, gva, INVALID_PAGE);
  4728. ++vcpu->stat.invlpg;
  4729. }
  4730. EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
  4731. void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
  4732. {
  4733. struct kvm_mmu *mmu = vcpu->arch.mmu;
  4734. bool tlb_flush = false;
  4735. uint i;
  4736. if (pcid == kvm_get_active_pcid(vcpu)) {
  4737. if (mmu->invlpg)
  4738. mmu->invlpg(vcpu, gva, mmu->root.hpa);
  4739. tlb_flush = true;
  4740. }
  4741. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
  4742. if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
  4743. pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
  4744. if (mmu->invlpg)
  4745. mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
  4746. tlb_flush = true;
  4747. }
  4748. }
  4749. if (tlb_flush)
  4750. static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
  4751. ++vcpu->stat.invlpg;
  4752. /*
  4753. * Mappings not reachable via the current cr3 or the prev_roots will be
  4754. * synced when switching to that cr3, so nothing needs to be done here
  4755. * for them.
  4756. */
  4757. }
  4758. void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
  4759. int tdp_max_root_level, int tdp_huge_page_level)
  4760. {
  4761. tdp_enabled = enable_tdp;
  4762. tdp_root_level = tdp_forced_root_level;
  4763. max_tdp_level = tdp_max_root_level;
  4764. /*
  4765. * max_huge_page_level reflects KVM's MMU capabilities irrespective
  4766. * of kernel support, e.g. KVM may be capable of using 1GB pages when
  4767. * the kernel is not. But, KVM never creates a page size greater than
  4768. * what is used by the kernel for any given HVA, i.e. the kernel's
  4769. * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
  4770. */
  4771. if (tdp_enabled)
  4772. max_huge_page_level = tdp_huge_page_level;
  4773. else if (boot_cpu_has(X86_FEATURE_GBPAGES))
  4774. max_huge_page_level = PG_LEVEL_1G;
  4775. else
  4776. max_huge_page_level = PG_LEVEL_2M;
  4777. }
  4778. EXPORT_SYMBOL_GPL(kvm_configure_mmu);
  4779. /* The return value indicates if tlb flush on all vcpus is needed. */
  4780. typedef bool (*slot_level_handler) (struct kvm *kvm,
  4781. struct kvm_rmap_head *rmap_head,
  4782. const struct kvm_memory_slot *slot);
  4783. /* The caller should hold mmu-lock before calling this function. */
  4784. static __always_inline bool
  4785. slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
  4786. slot_level_handler fn, int start_level, int end_level,
  4787. gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
  4788. bool flush)
  4789. {
  4790. struct slot_rmap_walk_iterator iterator;
  4791. for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
  4792. end_gfn, &iterator) {
  4793. if (iterator.rmap)
  4794. flush |= fn(kvm, iterator.rmap, memslot);
  4795. if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
  4796. if (flush && flush_on_yield) {
  4797. kvm_flush_remote_tlbs_with_address(kvm,
  4798. start_gfn,
  4799. iterator.gfn - start_gfn + 1);
  4800. flush = false;
  4801. }
  4802. cond_resched_rwlock_write(&kvm->mmu_lock);
  4803. }
  4804. }
  4805. return flush;
  4806. }
  4807. static __always_inline bool
  4808. slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
  4809. slot_level_handler fn, int start_level, int end_level,
  4810. bool flush_on_yield)
  4811. {
  4812. return slot_handle_level_range(kvm, memslot, fn, start_level,
  4813. end_level, memslot->base_gfn,
  4814. memslot->base_gfn + memslot->npages - 1,
  4815. flush_on_yield, false);
  4816. }
  4817. static __always_inline bool
  4818. slot_handle_level_4k(struct kvm *kvm, const struct kvm_memory_slot *memslot,
  4819. slot_level_handler fn, bool flush_on_yield)
  4820. {
  4821. return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
  4822. PG_LEVEL_4K, flush_on_yield);
  4823. }
  4824. static void free_mmu_pages(struct kvm_mmu *mmu)
  4825. {
  4826. if (!tdp_enabled && mmu->pae_root)
  4827. set_memory_encrypted((unsigned long)mmu->pae_root, 1);
  4828. free_page((unsigned long)mmu->pae_root);
  4829. free_page((unsigned long)mmu->pml4_root);
  4830. free_page((unsigned long)mmu->pml5_root);
  4831. }
  4832. static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
  4833. {
  4834. struct page *page;
  4835. int i;
  4836. mmu->root.hpa = INVALID_PAGE;
  4837. mmu->root.pgd = 0;
  4838. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  4839. mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
  4840. /* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
  4841. if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
  4842. return 0;
  4843. /*
  4844. * When using PAE paging, the four PDPTEs are treated as 'root' pages,
  4845. * while the PDP table is a per-vCPU construct that's allocated at MMU
  4846. * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
  4847. * x86_64. Therefore we need to allocate the PDP table in the first
  4848. * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
  4849. * generally doesn't use PAE paging and can skip allocating the PDP
  4850. * table. The main exception, handled here, is SVM's 32-bit NPT. The
  4851. * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
  4852. * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
  4853. */
  4854. if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
  4855. return 0;
  4856. page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
  4857. if (!page)
  4858. return -ENOMEM;
  4859. mmu->pae_root = page_address(page);
  4860. /*
  4861. * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
  4862. * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
  4863. * that KVM's writes and the CPU's reads get along. Note, this is
  4864. * only necessary when using shadow paging, as 64-bit NPT can get at
  4865. * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
  4866. * by 32-bit kernels (when KVM itself uses 32-bit NPT).
  4867. */
  4868. if (!tdp_enabled)
  4869. set_memory_decrypted((unsigned long)mmu->pae_root, 1);
  4870. else
  4871. WARN_ON_ONCE(shadow_me_value);
  4872. for (i = 0; i < 4; ++i)
  4873. mmu->pae_root[i] = INVALID_PAE_ROOT;
  4874. return 0;
  4875. }
  4876. int kvm_mmu_create(struct kvm_vcpu *vcpu)
  4877. {
  4878. int ret;
  4879. vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
  4880. vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
  4881. vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
  4882. vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
  4883. vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
  4884. vcpu->arch.mmu = &vcpu->arch.root_mmu;
  4885. vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
  4886. ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
  4887. if (ret)
  4888. return ret;
  4889. ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
  4890. if (ret)
  4891. goto fail_allocate_root;
  4892. return ret;
  4893. fail_allocate_root:
  4894. free_mmu_pages(&vcpu->arch.guest_mmu);
  4895. return ret;
  4896. }
  4897. #define BATCH_ZAP_PAGES 10
  4898. static void kvm_zap_obsolete_pages(struct kvm *kvm)
  4899. {
  4900. struct kvm_mmu_page *sp, *node;
  4901. int nr_zapped, batch = 0;
  4902. bool unstable;
  4903. restart:
  4904. list_for_each_entry_safe_reverse(sp, node,
  4905. &kvm->arch.active_mmu_pages, link) {
  4906. /*
  4907. * No obsolete valid page exists before a newly created page
  4908. * since active_mmu_pages is a FIFO list.
  4909. */
  4910. if (!is_obsolete_sp(kvm, sp))
  4911. break;
  4912. /*
  4913. * Invalid pages should never land back on the list of active
  4914. * pages. Skip the bogus page, otherwise we'll get stuck in an
  4915. * infinite loop if the page gets put back on the list (again).
  4916. */
  4917. if (WARN_ON(sp->role.invalid))
  4918. continue;
  4919. /*
  4920. * No need to flush the TLB since we're only zapping shadow
  4921. * pages with an obsolete generation number and all vCPUS have
  4922. * loaded a new root, i.e. the shadow pages being zapped cannot
  4923. * be in active use by the guest.
  4924. */
  4925. if (batch >= BATCH_ZAP_PAGES &&
  4926. cond_resched_rwlock_write(&kvm->mmu_lock)) {
  4927. batch = 0;
  4928. goto restart;
  4929. }
  4930. unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
  4931. &kvm->arch.zapped_obsolete_pages, &nr_zapped);
  4932. batch += nr_zapped;
  4933. if (unstable)
  4934. goto restart;
  4935. }
  4936. /*
  4937. * Kick all vCPUs (via remote TLB flush) before freeing the page tables
  4938. * to ensure KVM is not in the middle of a lockless shadow page table
  4939. * walk, which may reference the pages. The remote TLB flush itself is
  4940. * not required and is simply a convenient way to kick vCPUs as needed.
  4941. * KVM performs a local TLB flush when allocating a new root (see
  4942. * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
  4943. * running with an obsolete MMU.
  4944. */
  4945. kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
  4946. }
  4947. /*
  4948. * Fast invalidate all shadow pages and use lock-break technique
  4949. * to zap obsolete pages.
  4950. *
  4951. * It's required when memslot is being deleted or VM is being
  4952. * destroyed, in these cases, we should ensure that KVM MMU does
  4953. * not use any resource of the being-deleted slot or all slots
  4954. * after calling the function.
  4955. */
  4956. static void kvm_mmu_zap_all_fast(struct kvm *kvm)
  4957. {
  4958. lockdep_assert_held(&kvm->slots_lock);
  4959. write_lock(&kvm->mmu_lock);
  4960. trace_kvm_mmu_zap_all_fast(kvm);
  4961. /*
  4962. * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
  4963. * held for the entire duration of zapping obsolete pages, it's
  4964. * impossible for there to be multiple invalid generations associated
  4965. * with *valid* shadow pages at any given time, i.e. there is exactly
  4966. * one valid generation and (at most) one invalid generation.
  4967. */
  4968. kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
  4969. /*
  4970. * In order to ensure all vCPUs drop their soon-to-be invalid roots,
  4971. * invalidating TDP MMU roots must be done while holding mmu_lock for
  4972. * write and in the same critical section as making the reload request,
  4973. * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
  4974. */
  4975. if (is_tdp_mmu_enabled(kvm))
  4976. kvm_tdp_mmu_invalidate_all_roots(kvm);
  4977. /*
  4978. * Notify all vcpus to reload its shadow page table and flush TLB.
  4979. * Then all vcpus will switch to new shadow page table with the new
  4980. * mmu_valid_gen.
  4981. *
  4982. * Note: we need to do this under the protection of mmu_lock,
  4983. * otherwise, vcpu would purge shadow page but miss tlb flush.
  4984. */
  4985. kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
  4986. kvm_zap_obsolete_pages(kvm);
  4987. write_unlock(&kvm->mmu_lock);
  4988. /*
  4989. * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
  4990. * returning to the caller, e.g. if the zap is in response to a memslot
  4991. * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
  4992. * associated with the deleted memslot once the update completes, and
  4993. * Deferring the zap until the final reference to the root is put would
  4994. * lead to use-after-free.
  4995. */
  4996. if (is_tdp_mmu_enabled(kvm))
  4997. kvm_tdp_mmu_zap_invalidated_roots(kvm);
  4998. }
  4999. static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
  5000. {
  5001. return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
  5002. }
  5003. static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
  5004. struct kvm_memory_slot *slot,
  5005. struct kvm_page_track_notifier_node *node)
  5006. {
  5007. kvm_mmu_zap_all_fast(kvm);
  5008. }
  5009. void kvm_mmu_init_vm(struct kvm *kvm)
  5010. {
  5011. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  5012. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  5013. INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
  5014. INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
  5015. spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
  5016. kvm_mmu_init_tdp_mmu(kvm);
  5017. node->track_write = kvm_mmu_pte_write;
  5018. node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
  5019. kvm_page_track_register_notifier(kvm, node);
  5020. kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
  5021. kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
  5022. kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
  5023. kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
  5024. kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
  5025. }
  5026. static void mmu_free_vm_memory_caches(struct kvm *kvm)
  5027. {
  5028. kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
  5029. kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
  5030. kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
  5031. }
  5032. void kvm_mmu_uninit_vm(struct kvm *kvm)
  5033. {
  5034. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  5035. kvm_page_track_unregister_notifier(kvm, node);
  5036. kvm_mmu_uninit_tdp_mmu(kvm);
  5037. mmu_free_vm_memory_caches(kvm);
  5038. }
  5039. static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
  5040. {
  5041. const struct kvm_memory_slot *memslot;
  5042. struct kvm_memslots *slots;
  5043. struct kvm_memslot_iter iter;
  5044. bool flush = false;
  5045. gfn_t start, end;
  5046. int i;
  5047. if (!kvm_memslots_have_rmaps(kvm))
  5048. return flush;
  5049. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  5050. slots = __kvm_memslots(kvm, i);
  5051. kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
  5052. memslot = iter.slot;
  5053. start = max(gfn_start, memslot->base_gfn);
  5054. end = min(gfn_end, memslot->base_gfn + memslot->npages);
  5055. if (WARN_ON_ONCE(start >= end))
  5056. continue;
  5057. flush = slot_handle_level_range(kvm, memslot, __kvm_zap_rmap,
  5058. PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
  5059. start, end - 1, true, flush);
  5060. }
  5061. }
  5062. return flush;
  5063. }
  5064. /*
  5065. * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
  5066. * (not including it)
  5067. */
  5068. void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
  5069. {
  5070. bool flush;
  5071. if (WARN_ON_ONCE(gfn_end <= gfn_start))
  5072. return;
  5073. write_lock(&kvm->mmu_lock);
  5074. kvm_mmu_invalidate_begin(kvm, 0, -1ul);
  5075. flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
  5076. if (is_tdp_mmu_enabled(kvm))
  5077. flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
  5078. if (flush)
  5079. kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
  5080. gfn_end - gfn_start);
  5081. kvm_mmu_invalidate_end(kvm, 0, -1ul);
  5082. write_unlock(&kvm->mmu_lock);
  5083. }
  5084. static bool slot_rmap_write_protect(struct kvm *kvm,
  5085. struct kvm_rmap_head *rmap_head,
  5086. const struct kvm_memory_slot *slot)
  5087. {
  5088. return rmap_write_protect(rmap_head, false);
  5089. }
  5090. void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
  5091. const struct kvm_memory_slot *memslot,
  5092. int start_level)
  5093. {
  5094. if (kvm_memslots_have_rmaps(kvm)) {
  5095. write_lock(&kvm->mmu_lock);
  5096. slot_handle_level(kvm, memslot, slot_rmap_write_protect,
  5097. start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
  5098. write_unlock(&kvm->mmu_lock);
  5099. }
  5100. if (is_tdp_mmu_enabled(kvm)) {
  5101. read_lock(&kvm->mmu_lock);
  5102. kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
  5103. read_unlock(&kvm->mmu_lock);
  5104. }
  5105. }
  5106. static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
  5107. {
  5108. return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
  5109. }
  5110. static bool need_topup_split_caches_or_resched(struct kvm *kvm)
  5111. {
  5112. if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
  5113. return true;
  5114. /*
  5115. * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
  5116. * to split a single huge page. Calculating how many are actually needed
  5117. * is possible but not worth the complexity.
  5118. */
  5119. return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
  5120. need_topup(&kvm->arch.split_page_header_cache, 1) ||
  5121. need_topup(&kvm->arch.split_shadow_page_cache, 1);
  5122. }
  5123. static int topup_split_caches(struct kvm *kvm)
  5124. {
  5125. /*
  5126. * Allocating rmap list entries when splitting huge pages for nested
  5127. * MMUs is uncommon as KVM needs to use a list if and only if there is
  5128. * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
  5129. * aliased by multiple L2 gfns and/or from multiple nested roots with
  5130. * different roles. Aliasing gfns when using TDP is atypical for VMMs;
  5131. * a few gfns are often aliased during boot, e.g. when remapping BIOS,
  5132. * but aliasing rarely occurs post-boot or for many gfns. If there is
  5133. * only one rmap entry, rmap->val points directly at that one entry and
  5134. * doesn't need to allocate a list. Buffer the cache by the default
  5135. * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
  5136. * encounters an aliased gfn or two.
  5137. */
  5138. const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
  5139. KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
  5140. int r;
  5141. lockdep_assert_held(&kvm->slots_lock);
  5142. r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
  5143. SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
  5144. if (r)
  5145. return r;
  5146. r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
  5147. if (r)
  5148. return r;
  5149. return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
  5150. }
  5151. static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
  5152. {
  5153. struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
  5154. struct shadow_page_caches caches = {};
  5155. union kvm_mmu_page_role role;
  5156. unsigned int access;
  5157. gfn_t gfn;
  5158. gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
  5159. access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
  5160. /*
  5161. * Note, huge page splitting always uses direct shadow pages, regardless
  5162. * of whether the huge page itself is mapped by a direct or indirect
  5163. * shadow page, since the huge page region itself is being directly
  5164. * mapped with smaller pages.
  5165. */
  5166. role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
  5167. /* Direct SPs do not require a shadowed_info_cache. */
  5168. caches.page_header_cache = &kvm->arch.split_page_header_cache;
  5169. caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
  5170. /* Safe to pass NULL for vCPU since requesting a direct SP. */
  5171. return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
  5172. }
  5173. static void shadow_mmu_split_huge_page(struct kvm *kvm,
  5174. const struct kvm_memory_slot *slot,
  5175. u64 *huge_sptep)
  5176. {
  5177. struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
  5178. u64 huge_spte = READ_ONCE(*huge_sptep);
  5179. struct kvm_mmu_page *sp;
  5180. bool flush = false;
  5181. u64 *sptep, spte;
  5182. gfn_t gfn;
  5183. int index;
  5184. sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
  5185. for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
  5186. sptep = &sp->spt[index];
  5187. gfn = kvm_mmu_page_get_gfn(sp, index);
  5188. /*
  5189. * The SP may already have populated SPTEs, e.g. if this huge
  5190. * page is aliased by multiple sptes with the same access
  5191. * permissions. These entries are guaranteed to map the same
  5192. * gfn-to-pfn translation since the SP is direct, so no need to
  5193. * modify them.
  5194. *
  5195. * However, if a given SPTE points to a lower level page table,
  5196. * that lower level page table may only be partially populated.
  5197. * Installing such SPTEs would effectively unmap a potion of the
  5198. * huge page. Unmapping guest memory always requires a TLB flush
  5199. * since a subsequent operation on the unmapped regions would
  5200. * fail to detect the need to flush.
  5201. */
  5202. if (is_shadow_present_pte(*sptep)) {
  5203. flush |= !is_last_spte(*sptep, sp->role.level);
  5204. continue;
  5205. }
  5206. spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
  5207. mmu_spte_set(sptep, spte);
  5208. __rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
  5209. }
  5210. __link_shadow_page(kvm, cache, huge_sptep, sp, flush);
  5211. }
  5212. static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
  5213. const struct kvm_memory_slot *slot,
  5214. u64 *huge_sptep)
  5215. {
  5216. struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
  5217. int level, r = 0;
  5218. gfn_t gfn;
  5219. u64 spte;
  5220. /* Grab information for the tracepoint before dropping the MMU lock. */
  5221. gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
  5222. level = huge_sp->role.level;
  5223. spte = *huge_sptep;
  5224. if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
  5225. r = -ENOSPC;
  5226. goto out;
  5227. }
  5228. if (need_topup_split_caches_or_resched(kvm)) {
  5229. write_unlock(&kvm->mmu_lock);
  5230. cond_resched();
  5231. /*
  5232. * If the topup succeeds, return -EAGAIN to indicate that the
  5233. * rmap iterator should be restarted because the MMU lock was
  5234. * dropped.
  5235. */
  5236. r = topup_split_caches(kvm) ?: -EAGAIN;
  5237. write_lock(&kvm->mmu_lock);
  5238. goto out;
  5239. }
  5240. shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
  5241. out:
  5242. trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
  5243. return r;
  5244. }
  5245. static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
  5246. struct kvm_rmap_head *rmap_head,
  5247. const struct kvm_memory_slot *slot)
  5248. {
  5249. struct rmap_iterator iter;
  5250. struct kvm_mmu_page *sp;
  5251. u64 *huge_sptep;
  5252. int r;
  5253. restart:
  5254. for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
  5255. sp = sptep_to_sp(huge_sptep);
  5256. /* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
  5257. if (WARN_ON_ONCE(!sp->role.guest_mode))
  5258. continue;
  5259. /* The rmaps should never contain non-leaf SPTEs. */
  5260. if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
  5261. continue;
  5262. /* SPs with level >PG_LEVEL_4K should never by unsync. */
  5263. if (WARN_ON_ONCE(sp->unsync))
  5264. continue;
  5265. /* Don't bother splitting huge pages on invalid SPs. */
  5266. if (sp->role.invalid)
  5267. continue;
  5268. r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
  5269. /*
  5270. * The split succeeded or needs to be retried because the MMU
  5271. * lock was dropped. Either way, restart the iterator to get it
  5272. * back into a consistent state.
  5273. */
  5274. if (!r || r == -EAGAIN)
  5275. goto restart;
  5276. /* The split failed and shouldn't be retried (e.g. -ENOMEM). */
  5277. break;
  5278. }
  5279. return false;
  5280. }
  5281. static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
  5282. const struct kvm_memory_slot *slot,
  5283. gfn_t start, gfn_t end,
  5284. int target_level)
  5285. {
  5286. int level;
  5287. /*
  5288. * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
  5289. * down to the target level. This ensures pages are recursively split
  5290. * all the way to the target level. There's no need to split pages
  5291. * already at the target level.
  5292. */
  5293. for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--) {
  5294. slot_handle_level_range(kvm, slot, shadow_mmu_try_split_huge_pages,
  5295. level, level, start, end - 1, true, false);
  5296. }
  5297. }
  5298. /* Must be called with the mmu_lock held in write-mode. */
  5299. void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
  5300. const struct kvm_memory_slot *memslot,
  5301. u64 start, u64 end,
  5302. int target_level)
  5303. {
  5304. if (!is_tdp_mmu_enabled(kvm))
  5305. return;
  5306. if (kvm_memslots_have_rmaps(kvm))
  5307. kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
  5308. kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
  5309. /*
  5310. * A TLB flush is unnecessary at this point for the same resons as in
  5311. * kvm_mmu_slot_try_split_huge_pages().
  5312. */
  5313. }
  5314. void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
  5315. const struct kvm_memory_slot *memslot,
  5316. int target_level)
  5317. {
  5318. u64 start = memslot->base_gfn;
  5319. u64 end = start + memslot->npages;
  5320. if (!is_tdp_mmu_enabled(kvm))
  5321. return;
  5322. if (kvm_memslots_have_rmaps(kvm)) {
  5323. write_lock(&kvm->mmu_lock);
  5324. kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
  5325. write_unlock(&kvm->mmu_lock);
  5326. }
  5327. read_lock(&kvm->mmu_lock);
  5328. kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
  5329. read_unlock(&kvm->mmu_lock);
  5330. /*
  5331. * No TLB flush is necessary here. KVM will flush TLBs after
  5332. * write-protecting and/or clearing dirty on the newly split SPTEs to
  5333. * ensure that guest writes are reflected in the dirty log before the
  5334. * ioctl to enable dirty logging on this memslot completes. Since the
  5335. * split SPTEs retain the write and dirty bits of the huge SPTE, it is
  5336. * safe for KVM to decide if a TLB flush is necessary based on the split
  5337. * SPTEs.
  5338. */
  5339. }
  5340. static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
  5341. struct kvm_rmap_head *rmap_head,
  5342. const struct kvm_memory_slot *slot)
  5343. {
  5344. u64 *sptep;
  5345. struct rmap_iterator iter;
  5346. int need_tlb_flush = 0;
  5347. struct kvm_mmu_page *sp;
  5348. restart:
  5349. for_each_rmap_spte(rmap_head, &iter, sptep) {
  5350. sp = sptep_to_sp(sptep);
  5351. /*
  5352. * We cannot do huge page mapping for indirect shadow pages,
  5353. * which are found on the last rmap (level = 1) when not using
  5354. * tdp; such shadow pages are synced with the page table in
  5355. * the guest, and the guest page table is using 4K page size
  5356. * mapping if the indirect sp has level = 1.
  5357. */
  5358. if (sp->role.direct &&
  5359. sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
  5360. PG_LEVEL_NUM)) {
  5361. kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
  5362. if (kvm_available_flush_tlb_with_range())
  5363. kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
  5364. KVM_PAGES_PER_HPAGE(sp->role.level));
  5365. else
  5366. need_tlb_flush = 1;
  5367. goto restart;
  5368. }
  5369. }
  5370. return need_tlb_flush;
  5371. }
  5372. static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
  5373. const struct kvm_memory_slot *slot)
  5374. {
  5375. /*
  5376. * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
  5377. * pages that are already mapped at the maximum hugepage level.
  5378. */
  5379. if (slot_handle_level(kvm, slot, kvm_mmu_zap_collapsible_spte,
  5380. PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
  5381. kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
  5382. }
  5383. void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
  5384. const struct kvm_memory_slot *slot)
  5385. {
  5386. if (kvm_memslots_have_rmaps(kvm)) {
  5387. write_lock(&kvm->mmu_lock);
  5388. kvm_rmap_zap_collapsible_sptes(kvm, slot);
  5389. write_unlock(&kvm->mmu_lock);
  5390. }
  5391. if (is_tdp_mmu_enabled(kvm)) {
  5392. read_lock(&kvm->mmu_lock);
  5393. kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
  5394. read_unlock(&kvm->mmu_lock);
  5395. }
  5396. }
  5397. void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
  5398. const struct kvm_memory_slot *memslot)
  5399. {
  5400. /*
  5401. * All current use cases for flushing the TLBs for a specific memslot
  5402. * related to dirty logging, and many do the TLB flush out of mmu_lock.
  5403. * The interaction between the various operations on memslot must be
  5404. * serialized by slots_locks to ensure the TLB flush from one operation
  5405. * is observed by any other operation on the same memslot.
  5406. */
  5407. lockdep_assert_held(&kvm->slots_lock);
  5408. kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
  5409. memslot->npages);
  5410. }
  5411. void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
  5412. const struct kvm_memory_slot *memslot)
  5413. {
  5414. if (kvm_memslots_have_rmaps(kvm)) {
  5415. write_lock(&kvm->mmu_lock);
  5416. /*
  5417. * Clear dirty bits only on 4k SPTEs since the legacy MMU only
  5418. * support dirty logging at a 4k granularity.
  5419. */
  5420. slot_handle_level_4k(kvm, memslot, __rmap_clear_dirty, false);
  5421. write_unlock(&kvm->mmu_lock);
  5422. }
  5423. if (is_tdp_mmu_enabled(kvm)) {
  5424. read_lock(&kvm->mmu_lock);
  5425. kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
  5426. read_unlock(&kvm->mmu_lock);
  5427. }
  5428. /*
  5429. * The caller will flush the TLBs after this function returns.
  5430. *
  5431. * It's also safe to flush TLBs out of mmu lock here as currently this
  5432. * function is only used for dirty logging, in which case flushing TLB
  5433. * out of mmu lock also guarantees no dirty pages will be lost in
  5434. * dirty_bitmap.
  5435. */
  5436. }
  5437. void kvm_mmu_zap_all(struct kvm *kvm)
  5438. {
  5439. struct kvm_mmu_page *sp, *node;
  5440. LIST_HEAD(invalid_list);
  5441. int ign;
  5442. write_lock(&kvm->mmu_lock);
  5443. restart:
  5444. list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
  5445. if (WARN_ON(sp->role.invalid))
  5446. continue;
  5447. if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
  5448. goto restart;
  5449. if (cond_resched_rwlock_write(&kvm->mmu_lock))
  5450. goto restart;
  5451. }
  5452. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  5453. if (is_tdp_mmu_enabled(kvm))
  5454. kvm_tdp_mmu_zap_all(kvm);
  5455. write_unlock(&kvm->mmu_lock);
  5456. }
  5457. void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
  5458. {
  5459. WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
  5460. gen &= MMIO_SPTE_GEN_MASK;
  5461. /*
  5462. * Generation numbers are incremented in multiples of the number of
  5463. * address spaces in order to provide unique generations across all
  5464. * address spaces. Strip what is effectively the address space
  5465. * modifier prior to checking for a wrap of the MMIO generation so
  5466. * that a wrap in any address space is detected.
  5467. */
  5468. gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
  5469. /*
  5470. * The very rare case: if the MMIO generation number has wrapped,
  5471. * zap all shadow pages.
  5472. */
  5473. if (unlikely(gen == 0)) {
  5474. kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
  5475. kvm_mmu_zap_all_fast(kvm);
  5476. }
  5477. }
  5478. static unsigned long
  5479. mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  5480. {
  5481. struct kvm *kvm;
  5482. int nr_to_scan = sc->nr_to_scan;
  5483. unsigned long freed = 0;
  5484. mutex_lock(&kvm_lock);
  5485. list_for_each_entry(kvm, &vm_list, vm_list) {
  5486. int idx;
  5487. LIST_HEAD(invalid_list);
  5488. /*
  5489. * Never scan more than sc->nr_to_scan VM instances.
  5490. * Will not hit this condition practically since we do not try
  5491. * to shrink more than one VM and it is very unlikely to see
  5492. * !n_used_mmu_pages so many times.
  5493. */
  5494. if (!nr_to_scan--)
  5495. break;
  5496. /*
  5497. * n_used_mmu_pages is accessed without holding kvm->mmu_lock
  5498. * here. We may skip a VM instance errorneosly, but we do not
  5499. * want to shrink a VM that only started to populate its MMU
  5500. * anyway.
  5501. */
  5502. if (!kvm->arch.n_used_mmu_pages &&
  5503. !kvm_has_zapped_obsolete_pages(kvm))
  5504. continue;
  5505. idx = srcu_read_lock(&kvm->srcu);
  5506. write_lock(&kvm->mmu_lock);
  5507. if (kvm_has_zapped_obsolete_pages(kvm)) {
  5508. kvm_mmu_commit_zap_page(kvm,
  5509. &kvm->arch.zapped_obsolete_pages);
  5510. goto unlock;
  5511. }
  5512. freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
  5513. unlock:
  5514. write_unlock(&kvm->mmu_lock);
  5515. srcu_read_unlock(&kvm->srcu, idx);
  5516. /*
  5517. * unfair on small ones
  5518. * per-vm shrinkers cry out
  5519. * sadness comes quickly
  5520. */
  5521. list_move_tail(&kvm->vm_list, &vm_list);
  5522. break;
  5523. }
  5524. mutex_unlock(&kvm_lock);
  5525. return freed;
  5526. }
  5527. static unsigned long
  5528. mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  5529. {
  5530. return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
  5531. }
  5532. static struct shrinker mmu_shrinker = {
  5533. .count_objects = mmu_shrink_count,
  5534. .scan_objects = mmu_shrink_scan,
  5535. .seeks = DEFAULT_SEEKS * 10,
  5536. };
  5537. static void mmu_destroy_caches(void)
  5538. {
  5539. kmem_cache_destroy(pte_list_desc_cache);
  5540. kmem_cache_destroy(mmu_page_header_cache);
  5541. }
  5542. static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
  5543. {
  5544. if (nx_hugepage_mitigation_hard_disabled)
  5545. return sprintf(buffer, "never\n");
  5546. return param_get_bool(buffer, kp);
  5547. }
  5548. static bool get_nx_auto_mode(void)
  5549. {
  5550. /* Return true when CPU has the bug, and mitigations are ON */
  5551. return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
  5552. }
  5553. static void __set_nx_huge_pages(bool val)
  5554. {
  5555. nx_huge_pages = itlb_multihit_kvm_mitigation = val;
  5556. }
  5557. static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
  5558. {
  5559. bool old_val = nx_huge_pages;
  5560. bool new_val;
  5561. if (nx_hugepage_mitigation_hard_disabled)
  5562. return -EPERM;
  5563. /* In "auto" mode deploy workaround only if CPU has the bug. */
  5564. if (sysfs_streq(val, "off")) {
  5565. new_val = 0;
  5566. } else if (sysfs_streq(val, "force")) {
  5567. new_val = 1;
  5568. } else if (sysfs_streq(val, "auto")) {
  5569. new_val = get_nx_auto_mode();
  5570. } else if (sysfs_streq(val, "never")) {
  5571. new_val = 0;
  5572. mutex_lock(&kvm_lock);
  5573. if (!list_empty(&vm_list)) {
  5574. mutex_unlock(&kvm_lock);
  5575. return -EBUSY;
  5576. }
  5577. nx_hugepage_mitigation_hard_disabled = true;
  5578. mutex_unlock(&kvm_lock);
  5579. } else if (kstrtobool(val, &new_val) < 0) {
  5580. return -EINVAL;
  5581. }
  5582. __set_nx_huge_pages(new_val);
  5583. if (new_val != old_val) {
  5584. struct kvm *kvm;
  5585. mutex_lock(&kvm_lock);
  5586. list_for_each_entry(kvm, &vm_list, vm_list) {
  5587. mutex_lock(&kvm->slots_lock);
  5588. kvm_mmu_zap_all_fast(kvm);
  5589. mutex_unlock(&kvm->slots_lock);
  5590. wake_up_process(kvm->arch.nx_lpage_recovery_thread);
  5591. }
  5592. mutex_unlock(&kvm_lock);
  5593. }
  5594. return 0;
  5595. }
  5596. /*
  5597. * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
  5598. * its default value of -1 is technically undefined behavior for a boolean.
  5599. * Forward the module init call to SPTE code so that it too can handle module
  5600. * params that need to be resolved/snapshot.
  5601. */
  5602. void __init kvm_mmu_x86_module_init(void)
  5603. {
  5604. if (nx_huge_pages == -1)
  5605. __set_nx_huge_pages(get_nx_auto_mode());
  5606. kvm_mmu_spte_module_init();
  5607. }
  5608. /*
  5609. * The bulk of the MMU initialization is deferred until the vendor module is
  5610. * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
  5611. * to be reset when a potentially different vendor module is loaded.
  5612. */
  5613. int kvm_mmu_vendor_module_init(void)
  5614. {
  5615. int ret = -ENOMEM;
  5616. /*
  5617. * MMU roles use union aliasing which is, generally speaking, an
  5618. * undefined behavior. However, we supposedly know how compilers behave
  5619. * and the current status quo is unlikely to change. Guardians below are
  5620. * supposed to let us know if the assumption becomes false.
  5621. */
  5622. BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
  5623. BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
  5624. BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
  5625. kvm_mmu_reset_all_pte_masks();
  5626. pte_list_desc_cache = kmem_cache_create("pte_list_desc",
  5627. sizeof(struct pte_list_desc),
  5628. 0, SLAB_ACCOUNT, NULL);
  5629. if (!pte_list_desc_cache)
  5630. goto out;
  5631. mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
  5632. sizeof(struct kvm_mmu_page),
  5633. 0, SLAB_ACCOUNT, NULL);
  5634. if (!mmu_page_header_cache)
  5635. goto out;
  5636. if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
  5637. goto out;
  5638. ret = register_shrinker(&mmu_shrinker, "x86-mmu");
  5639. if (ret)
  5640. goto out_shrinker;
  5641. return 0;
  5642. out_shrinker:
  5643. percpu_counter_destroy(&kvm_total_used_mmu_pages);
  5644. out:
  5645. mmu_destroy_caches();
  5646. return ret;
  5647. }
  5648. void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
  5649. {
  5650. kvm_mmu_unload(vcpu);
  5651. free_mmu_pages(&vcpu->arch.root_mmu);
  5652. free_mmu_pages(&vcpu->arch.guest_mmu);
  5653. mmu_free_memory_caches(vcpu);
  5654. }
  5655. void kvm_mmu_vendor_module_exit(void)
  5656. {
  5657. mmu_destroy_caches();
  5658. percpu_counter_destroy(&kvm_total_used_mmu_pages);
  5659. unregister_shrinker(&mmu_shrinker);
  5660. }
  5661. /*
  5662. * Calculate the effective recovery period, accounting for '0' meaning "let KVM
  5663. * select a halving time of 1 hour". Returns true if recovery is enabled.
  5664. */
  5665. static bool calc_nx_huge_pages_recovery_period(uint *period)
  5666. {
  5667. /*
  5668. * Use READ_ONCE to get the params, this may be called outside of the
  5669. * param setters, e.g. by the kthread to compute its next timeout.
  5670. */
  5671. bool enabled = READ_ONCE(nx_huge_pages);
  5672. uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
  5673. if (!enabled || !ratio)
  5674. return false;
  5675. *period = READ_ONCE(nx_huge_pages_recovery_period_ms);
  5676. if (!*period) {
  5677. /* Make sure the period is not less than one second. */
  5678. ratio = min(ratio, 3600u);
  5679. *period = 60 * 60 * 1000 / ratio;
  5680. }
  5681. return true;
  5682. }
  5683. static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
  5684. {
  5685. bool was_recovery_enabled, is_recovery_enabled;
  5686. uint old_period, new_period;
  5687. int err;
  5688. if (nx_hugepage_mitigation_hard_disabled)
  5689. return -EPERM;
  5690. was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
  5691. err = param_set_uint(val, kp);
  5692. if (err)
  5693. return err;
  5694. is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
  5695. if (is_recovery_enabled &&
  5696. (!was_recovery_enabled || old_period > new_period)) {
  5697. struct kvm *kvm;
  5698. mutex_lock(&kvm_lock);
  5699. list_for_each_entry(kvm, &vm_list, vm_list)
  5700. wake_up_process(kvm->arch.nx_lpage_recovery_thread);
  5701. mutex_unlock(&kvm_lock);
  5702. }
  5703. return err;
  5704. }
  5705. static void kvm_recover_nx_lpages(struct kvm *kvm)
  5706. {
  5707. unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
  5708. int rcu_idx;
  5709. struct kvm_mmu_page *sp;
  5710. unsigned int ratio;
  5711. LIST_HEAD(invalid_list);
  5712. bool flush = false;
  5713. ulong to_zap;
  5714. rcu_idx = srcu_read_lock(&kvm->srcu);
  5715. write_lock(&kvm->mmu_lock);
  5716. /*
  5717. * Zapping TDP MMU shadow pages, including the remote TLB flush, must
  5718. * be done under RCU protection, because the pages are freed via RCU
  5719. * callback.
  5720. */
  5721. rcu_read_lock();
  5722. ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
  5723. to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
  5724. for ( ; to_zap; --to_zap) {
  5725. if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
  5726. break;
  5727. /*
  5728. * We use a separate list instead of just using active_mmu_pages
  5729. * because the number of lpage_disallowed pages is expected to
  5730. * be relatively small compared to the total.
  5731. */
  5732. sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
  5733. struct kvm_mmu_page,
  5734. lpage_disallowed_link);
  5735. WARN_ON_ONCE(!sp->lpage_disallowed);
  5736. if (is_tdp_mmu_page(sp)) {
  5737. flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
  5738. } else {
  5739. kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
  5740. WARN_ON_ONCE(sp->lpage_disallowed);
  5741. }
  5742. if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
  5743. kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
  5744. rcu_read_unlock();
  5745. cond_resched_rwlock_write(&kvm->mmu_lock);
  5746. flush = false;
  5747. rcu_read_lock();
  5748. }
  5749. }
  5750. kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
  5751. rcu_read_unlock();
  5752. write_unlock(&kvm->mmu_lock);
  5753. srcu_read_unlock(&kvm->srcu, rcu_idx);
  5754. }
  5755. static long get_nx_lpage_recovery_timeout(u64 start_time)
  5756. {
  5757. bool enabled;
  5758. uint period;
  5759. enabled = calc_nx_huge_pages_recovery_period(&period);
  5760. return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
  5761. : MAX_SCHEDULE_TIMEOUT;
  5762. }
  5763. static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
  5764. {
  5765. u64 start_time;
  5766. long remaining_time;
  5767. while (true) {
  5768. start_time = get_jiffies_64();
  5769. remaining_time = get_nx_lpage_recovery_timeout(start_time);
  5770. set_current_state(TASK_INTERRUPTIBLE);
  5771. while (!kthread_should_stop() && remaining_time > 0) {
  5772. schedule_timeout(remaining_time);
  5773. remaining_time = get_nx_lpage_recovery_timeout(start_time);
  5774. set_current_state(TASK_INTERRUPTIBLE);
  5775. }
  5776. set_current_state(TASK_RUNNING);
  5777. if (kthread_should_stop())
  5778. return 0;
  5779. kvm_recover_nx_lpages(kvm);
  5780. }
  5781. }
  5782. int kvm_mmu_post_init_vm(struct kvm *kvm)
  5783. {
  5784. int err;
  5785. if (nx_hugepage_mitigation_hard_disabled)
  5786. return 0;
  5787. err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
  5788. "kvm-nx-lpage-recovery",
  5789. &kvm->arch.nx_lpage_recovery_thread);
  5790. if (!err)
  5791. kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
  5792. return err;
  5793. }
  5794. void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
  5795. {
  5796. if (kvm->arch.nx_lpage_recovery_thread)
  5797. kthread_stop(kvm->arch.nx_lpage_recovery_thread);
  5798. }