mmu.c 164 KB

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