mmu.c 153 KB

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