vmx.c 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Kernel-based Virtual Machine driver for Linux
  4. *
  5. * This module enables machines with Intel VT-x extensions to run virtual
  6. * machines without emulation or binary translation.
  7. *
  8. * Copyright (C) 2006 Qumranet, Inc.
  9. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  10. *
  11. * Authors:
  12. * Avi Kivity <[email protected]>
  13. * Yaniv Kamay <[email protected]>
  14. */
  15. #include <linux/highmem.h>
  16. #include <linux/hrtimer.h>
  17. #include <linux/kernel.h>
  18. #include <linux/kvm_host.h>
  19. #include <linux/module.h>
  20. #include <linux/moduleparam.h>
  21. #include <linux/mod_devicetable.h>
  22. #include <linux/mm.h>
  23. #include <linux/objtool.h>
  24. #include <linux/sched.h>
  25. #include <linux/sched/smt.h>
  26. #include <linux/slab.h>
  27. #include <linux/tboot.h>
  28. #include <linux/trace_events.h>
  29. #include <linux/entry-kvm.h>
  30. #include <asm/apic.h>
  31. #include <asm/asm.h>
  32. #include <asm/cpu.h>
  33. #include <asm/cpu_device_id.h>
  34. #include <asm/debugreg.h>
  35. #include <asm/desc.h>
  36. #include <asm/fpu/api.h>
  37. #include <asm/fpu/xstate.h>
  38. #include <asm/idtentry.h>
  39. #include <asm/io.h>
  40. #include <asm/irq_remapping.h>
  41. #include <asm/reboot.h>
  42. #include <asm/perf_event.h>
  43. #include <asm/mmu_context.h>
  44. #include <asm/mshyperv.h>
  45. #include <asm/mwait.h>
  46. #include <asm/spec-ctrl.h>
  47. #include <asm/virtext.h>
  48. #include <asm/vmx.h>
  49. #include "capabilities.h"
  50. #include "cpuid.h"
  51. #include "evmcs.h"
  52. #include "hyperv.h"
  53. #include "kvm_onhyperv.h"
  54. #include "irq.h"
  55. #include "kvm_cache_regs.h"
  56. #include "lapic.h"
  57. #include "mmu.h"
  58. #include "nested.h"
  59. #include "pmu.h"
  60. #include "sgx.h"
  61. #include "trace.h"
  62. #include "vmcs.h"
  63. #include "vmcs12.h"
  64. #include "vmx.h"
  65. #include "x86.h"
  66. MODULE_AUTHOR("Qumranet");
  67. MODULE_LICENSE("GPL");
  68. #ifdef MODULE
  69. static const struct x86_cpu_id vmx_cpu_id[] = {
  70. X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
  71. {}
  72. };
  73. MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
  74. #endif
  75. bool __read_mostly enable_vpid = 1;
  76. module_param_named(vpid, enable_vpid, bool, 0444);
  77. static bool __read_mostly enable_vnmi = 1;
  78. module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
  79. bool __read_mostly flexpriority_enabled = 1;
  80. module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
  81. bool __read_mostly enable_ept = 1;
  82. module_param_named(ept, enable_ept, bool, S_IRUGO);
  83. bool __read_mostly enable_unrestricted_guest = 1;
  84. module_param_named(unrestricted_guest,
  85. enable_unrestricted_guest, bool, S_IRUGO);
  86. bool __read_mostly enable_ept_ad_bits = 1;
  87. module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
  88. static bool __read_mostly emulate_invalid_guest_state = true;
  89. module_param(emulate_invalid_guest_state, bool, S_IRUGO);
  90. static bool __read_mostly fasteoi = 1;
  91. module_param(fasteoi, bool, S_IRUGO);
  92. module_param(enable_apicv, bool, S_IRUGO);
  93. bool __read_mostly enable_ipiv = true;
  94. module_param(enable_ipiv, bool, 0444);
  95. /*
  96. * If nested=1, nested virtualization is supported, i.e., guests may use
  97. * VMX and be a hypervisor for its own guests. If nested=0, guests may not
  98. * use VMX instructions.
  99. */
  100. static bool __read_mostly nested = 1;
  101. module_param(nested, bool, S_IRUGO);
  102. bool __read_mostly enable_pml = 1;
  103. module_param_named(pml, enable_pml, bool, S_IRUGO);
  104. static bool __read_mostly error_on_inconsistent_vmcs_config = true;
  105. module_param(error_on_inconsistent_vmcs_config, bool, 0444);
  106. static bool __read_mostly dump_invalid_vmcs = 0;
  107. module_param(dump_invalid_vmcs, bool, 0644);
  108. #define MSR_BITMAP_MODE_X2APIC 1
  109. #define MSR_BITMAP_MODE_X2APIC_APICV 2
  110. #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
  111. /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
  112. static int __read_mostly cpu_preemption_timer_multi;
  113. static bool __read_mostly enable_preemption_timer = 1;
  114. #ifdef CONFIG_X86_64
  115. module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
  116. #endif
  117. extern bool __read_mostly allow_smaller_maxphyaddr;
  118. module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
  119. #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
  120. #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
  121. #define KVM_VM_CR0_ALWAYS_ON \
  122. (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
  123. #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
  124. #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
  125. #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
  126. #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
  127. #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
  128. RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
  129. RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
  130. RTIT_STATUS_BYTECNT))
  131. /*
  132. * List of MSRs that can be directly passed to the guest.
  133. * In addition to these x2apic and PT MSRs are handled specially.
  134. */
  135. static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
  136. MSR_IA32_SPEC_CTRL,
  137. MSR_IA32_PRED_CMD,
  138. MSR_IA32_TSC,
  139. #ifdef CONFIG_X86_64
  140. MSR_FS_BASE,
  141. MSR_GS_BASE,
  142. MSR_KERNEL_GS_BASE,
  143. MSR_IA32_XFD,
  144. MSR_IA32_XFD_ERR,
  145. #endif
  146. MSR_IA32_SYSENTER_CS,
  147. MSR_IA32_SYSENTER_ESP,
  148. MSR_IA32_SYSENTER_EIP,
  149. MSR_CORE_C1_RES,
  150. MSR_CORE_C3_RESIDENCY,
  151. MSR_CORE_C6_RESIDENCY,
  152. MSR_CORE_C7_RESIDENCY,
  153. };
  154. /*
  155. * These 2 parameters are used to config the controls for Pause-Loop Exiting:
  156. * ple_gap: upper bound on the amount of time between two successive
  157. * executions of PAUSE in a loop. Also indicate if ple enabled.
  158. * According to test, this time is usually smaller than 128 cycles.
  159. * ple_window: upper bound on the amount of time a guest is allowed to execute
  160. * in a PAUSE loop. Tests indicate that most spinlocks are held for
  161. * less than 2^12 cycles
  162. * Time is measured based on a counter that runs at the same rate as the TSC,
  163. * refer SDM volume 3b section 21.6.13 & 22.1.3.
  164. */
  165. static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
  166. module_param(ple_gap, uint, 0444);
  167. static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
  168. module_param(ple_window, uint, 0444);
  169. /* Default doubles per-vcpu window every exit. */
  170. static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
  171. module_param(ple_window_grow, uint, 0444);
  172. /* Default resets per-vcpu window every exit to ple_window. */
  173. static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
  174. module_param(ple_window_shrink, uint, 0444);
  175. /* Default is to compute the maximum so we can never overflow. */
  176. static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
  177. module_param(ple_window_max, uint, 0444);
  178. /* Default is SYSTEM mode, 1 for host-guest mode */
  179. int __read_mostly pt_mode = PT_MODE_SYSTEM;
  180. module_param(pt_mode, int, S_IRUGO);
  181. static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
  182. static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
  183. static DEFINE_MUTEX(vmx_l1d_flush_mutex);
  184. /* Storage for pre module init parameter parsing */
  185. static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
  186. static const struct {
  187. const char *option;
  188. bool for_parse;
  189. } vmentry_l1d_param[] = {
  190. [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
  191. [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
  192. [VMENTER_L1D_FLUSH_COND] = {"cond", true},
  193. [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
  194. [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
  195. [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
  196. };
  197. #define L1D_CACHE_ORDER 4
  198. static void *vmx_l1d_flush_pages;
  199. /* Control for disabling CPU Fill buffer clear */
  200. static bool __read_mostly vmx_fb_clear_ctrl_available;
  201. static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
  202. {
  203. struct page *page;
  204. unsigned int i;
  205. if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
  206. l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
  207. return 0;
  208. }
  209. if (!enable_ept) {
  210. l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
  211. return 0;
  212. }
  213. if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
  214. u64 msr;
  215. rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
  216. if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
  217. l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
  218. return 0;
  219. }
  220. }
  221. /* If set to auto use the default l1tf mitigation method */
  222. if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
  223. switch (l1tf_mitigation) {
  224. case L1TF_MITIGATION_OFF:
  225. l1tf = VMENTER_L1D_FLUSH_NEVER;
  226. break;
  227. case L1TF_MITIGATION_FLUSH_NOWARN:
  228. case L1TF_MITIGATION_FLUSH:
  229. case L1TF_MITIGATION_FLUSH_NOSMT:
  230. l1tf = VMENTER_L1D_FLUSH_COND;
  231. break;
  232. case L1TF_MITIGATION_FULL:
  233. case L1TF_MITIGATION_FULL_FORCE:
  234. l1tf = VMENTER_L1D_FLUSH_ALWAYS;
  235. break;
  236. }
  237. } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
  238. l1tf = VMENTER_L1D_FLUSH_ALWAYS;
  239. }
  240. if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
  241. !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
  242. /*
  243. * This allocation for vmx_l1d_flush_pages is not tied to a VM
  244. * lifetime and so should not be charged to a memcg.
  245. */
  246. page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
  247. if (!page)
  248. return -ENOMEM;
  249. vmx_l1d_flush_pages = page_address(page);
  250. /*
  251. * Initialize each page with a different pattern in
  252. * order to protect against KSM in the nested
  253. * virtualization case.
  254. */
  255. for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
  256. memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
  257. PAGE_SIZE);
  258. }
  259. }
  260. l1tf_vmx_mitigation = l1tf;
  261. if (l1tf != VMENTER_L1D_FLUSH_NEVER)
  262. static_branch_enable(&vmx_l1d_should_flush);
  263. else
  264. static_branch_disable(&vmx_l1d_should_flush);
  265. if (l1tf == VMENTER_L1D_FLUSH_COND)
  266. static_branch_enable(&vmx_l1d_flush_cond);
  267. else
  268. static_branch_disable(&vmx_l1d_flush_cond);
  269. return 0;
  270. }
  271. static int vmentry_l1d_flush_parse(const char *s)
  272. {
  273. unsigned int i;
  274. if (s) {
  275. for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
  276. if (vmentry_l1d_param[i].for_parse &&
  277. sysfs_streq(s, vmentry_l1d_param[i].option))
  278. return i;
  279. }
  280. }
  281. return -EINVAL;
  282. }
  283. static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
  284. {
  285. int l1tf, ret;
  286. l1tf = vmentry_l1d_flush_parse(s);
  287. if (l1tf < 0)
  288. return l1tf;
  289. if (!boot_cpu_has(X86_BUG_L1TF))
  290. return 0;
  291. /*
  292. * Has vmx_init() run already? If not then this is the pre init
  293. * parameter parsing. In that case just store the value and let
  294. * vmx_init() do the proper setup after enable_ept has been
  295. * established.
  296. */
  297. if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
  298. vmentry_l1d_flush_param = l1tf;
  299. return 0;
  300. }
  301. mutex_lock(&vmx_l1d_flush_mutex);
  302. ret = vmx_setup_l1d_flush(l1tf);
  303. mutex_unlock(&vmx_l1d_flush_mutex);
  304. return ret;
  305. }
  306. static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
  307. {
  308. if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
  309. return sprintf(s, "???\n");
  310. return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
  311. }
  312. static void vmx_setup_fb_clear_ctrl(void)
  313. {
  314. u64 msr;
  315. if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
  316. !boot_cpu_has_bug(X86_BUG_MDS) &&
  317. !boot_cpu_has_bug(X86_BUG_TAA)) {
  318. rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
  319. if (msr & ARCH_CAP_FB_CLEAR_CTRL)
  320. vmx_fb_clear_ctrl_available = true;
  321. }
  322. }
  323. static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
  324. {
  325. u64 msr;
  326. if (!vmx->disable_fb_clear)
  327. return;
  328. msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
  329. msr |= FB_CLEAR_DIS;
  330. native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
  331. /* Cache the MSR value to avoid reading it later */
  332. vmx->msr_ia32_mcu_opt_ctrl = msr;
  333. }
  334. static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
  335. {
  336. if (!vmx->disable_fb_clear)
  337. return;
  338. vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
  339. native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
  340. }
  341. static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
  342. {
  343. vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
  344. /*
  345. * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
  346. * at VMEntry. Skip the MSR read/write when a guest has no use case to
  347. * execute VERW.
  348. */
  349. if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
  350. ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
  351. (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
  352. (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
  353. (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
  354. (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
  355. vmx->disable_fb_clear = false;
  356. }
  357. static const struct kernel_param_ops vmentry_l1d_flush_ops = {
  358. .set = vmentry_l1d_flush_set,
  359. .get = vmentry_l1d_flush_get,
  360. };
  361. module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
  362. static u32 vmx_segment_access_rights(struct kvm_segment *var);
  363. void vmx_vmexit(void);
  364. #define vmx_insn_failed(fmt...) \
  365. do { \
  366. WARN_ONCE(1, fmt); \
  367. pr_warn_ratelimited(fmt); \
  368. } while (0)
  369. void vmread_error(unsigned long field, bool fault)
  370. {
  371. if (fault)
  372. kvm_spurious_fault();
  373. else
  374. vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
  375. }
  376. noinline void vmwrite_error(unsigned long field, unsigned long value)
  377. {
  378. vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%u\n",
  379. field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
  380. }
  381. noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
  382. {
  383. vmx_insn_failed("kvm: vmclear failed: %p/%llx err=%u\n",
  384. vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
  385. }
  386. noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
  387. {
  388. vmx_insn_failed("kvm: vmptrld failed: %p/%llx err=%u\n",
  389. vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
  390. }
  391. noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
  392. {
  393. vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
  394. ext, vpid, gva);
  395. }
  396. noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
  397. {
  398. vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
  399. ext, eptp, gpa);
  400. }
  401. static DEFINE_PER_CPU(struct vmcs *, vmxarea);
  402. DEFINE_PER_CPU(struct vmcs *, current_vmcs);
  403. /*
  404. * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
  405. * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
  406. */
  407. static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
  408. static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
  409. static DEFINE_SPINLOCK(vmx_vpid_lock);
  410. struct vmcs_config vmcs_config;
  411. struct vmx_capability vmx_capability;
  412. #define VMX_SEGMENT_FIELD(seg) \
  413. [VCPU_SREG_##seg] = { \
  414. .selector = GUEST_##seg##_SELECTOR, \
  415. .base = GUEST_##seg##_BASE, \
  416. .limit = GUEST_##seg##_LIMIT, \
  417. .ar_bytes = GUEST_##seg##_AR_BYTES, \
  418. }
  419. static const struct kvm_vmx_segment_field {
  420. unsigned selector;
  421. unsigned base;
  422. unsigned limit;
  423. unsigned ar_bytes;
  424. } kvm_vmx_segment_fields[] = {
  425. VMX_SEGMENT_FIELD(CS),
  426. VMX_SEGMENT_FIELD(DS),
  427. VMX_SEGMENT_FIELD(ES),
  428. VMX_SEGMENT_FIELD(FS),
  429. VMX_SEGMENT_FIELD(GS),
  430. VMX_SEGMENT_FIELD(SS),
  431. VMX_SEGMENT_FIELD(TR),
  432. VMX_SEGMENT_FIELD(LDTR),
  433. };
  434. static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
  435. {
  436. vmx->segment_cache.bitmask = 0;
  437. }
  438. static unsigned long host_idt_base;
  439. #if IS_ENABLED(CONFIG_HYPERV)
  440. static bool __read_mostly enlightened_vmcs = true;
  441. module_param(enlightened_vmcs, bool, 0444);
  442. static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
  443. {
  444. struct hv_enlightened_vmcs *evmcs;
  445. struct hv_partition_assist_pg **p_hv_pa_pg =
  446. &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
  447. /*
  448. * Synthetic VM-Exit is not enabled in current code and so All
  449. * evmcs in singe VM shares same assist page.
  450. */
  451. if (!*p_hv_pa_pg)
  452. *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
  453. if (!*p_hv_pa_pg)
  454. return -ENOMEM;
  455. evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
  456. evmcs->partition_assist_page =
  457. __pa(*p_hv_pa_pg);
  458. evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
  459. evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
  460. return 0;
  461. }
  462. static void hv_reset_evmcs(void)
  463. {
  464. struct hv_vp_assist_page *vp_ap;
  465. if (!static_branch_unlikely(&enable_evmcs))
  466. return;
  467. /*
  468. * KVM should enable eVMCS if and only if all CPUs have a VP assist
  469. * page, and should reject CPU onlining if eVMCS is enabled the CPU
  470. * doesn't have a VP assist page allocated.
  471. */
  472. vp_ap = hv_get_vp_assist_page(smp_processor_id());
  473. if (WARN_ON_ONCE(!vp_ap))
  474. return;
  475. /*
  476. * Reset everything to support using non-enlightened VMCS access later
  477. * (e.g. when we reload the module with enlightened_vmcs=0)
  478. */
  479. vp_ap->nested_control.features.directhypercall = 0;
  480. vp_ap->current_nested_vmcs = 0;
  481. vp_ap->enlighten_vmentry = 0;
  482. }
  483. #else /* IS_ENABLED(CONFIG_HYPERV) */
  484. static void hv_reset_evmcs(void) {}
  485. #endif /* IS_ENABLED(CONFIG_HYPERV) */
  486. /*
  487. * Comment's format: document - errata name - stepping - processor name.
  488. * Refer from
  489. * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
  490. */
  491. static u32 vmx_preemption_cpu_tfms[] = {
  492. /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
  493. 0x000206E6,
  494. /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
  495. /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
  496. /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
  497. 0x00020652,
  498. /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
  499. 0x00020655,
  500. /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
  501. /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
  502. /*
  503. * 320767.pdf - AAP86 - B1 -
  504. * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
  505. */
  506. 0x000106E5,
  507. /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
  508. 0x000106A0,
  509. /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
  510. 0x000106A1,
  511. /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
  512. 0x000106A4,
  513. /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
  514. /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
  515. /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
  516. 0x000106A5,
  517. /* Xeon E3-1220 V2 */
  518. 0x000306A8,
  519. };
  520. static inline bool cpu_has_broken_vmx_preemption_timer(void)
  521. {
  522. u32 eax = cpuid_eax(0x00000001), i;
  523. /* Clear the reserved bits */
  524. eax &= ~(0x3U << 14 | 0xfU << 28);
  525. for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
  526. if (eax == vmx_preemption_cpu_tfms[i])
  527. return true;
  528. return false;
  529. }
  530. static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
  531. {
  532. return flexpriority_enabled && lapic_in_kernel(vcpu);
  533. }
  534. static int possible_passthrough_msr_slot(u32 msr)
  535. {
  536. u32 i;
  537. for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
  538. if (vmx_possible_passthrough_msrs[i] == msr)
  539. return i;
  540. return -ENOENT;
  541. }
  542. static bool is_valid_passthrough_msr(u32 msr)
  543. {
  544. bool r;
  545. switch (msr) {
  546. case 0x800 ... 0x8ff:
  547. /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
  548. return true;
  549. case MSR_IA32_RTIT_STATUS:
  550. case MSR_IA32_RTIT_OUTPUT_BASE:
  551. case MSR_IA32_RTIT_OUTPUT_MASK:
  552. case MSR_IA32_RTIT_CR3_MATCH:
  553. case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
  554. /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
  555. case MSR_LBR_SELECT:
  556. case MSR_LBR_TOS:
  557. case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
  558. case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
  559. case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
  560. case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
  561. case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
  562. /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
  563. return true;
  564. }
  565. r = possible_passthrough_msr_slot(msr) != -ENOENT;
  566. WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
  567. return r;
  568. }
  569. struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
  570. {
  571. int i;
  572. i = kvm_find_user_return_msr(msr);
  573. if (i >= 0)
  574. return &vmx->guest_uret_msrs[i];
  575. return NULL;
  576. }
  577. static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
  578. struct vmx_uret_msr *msr, u64 data)
  579. {
  580. unsigned int slot = msr - vmx->guest_uret_msrs;
  581. int ret = 0;
  582. if (msr->load_into_hardware) {
  583. preempt_disable();
  584. ret = kvm_set_user_return_msr(slot, data, msr->mask);
  585. preempt_enable();
  586. }
  587. if (!ret)
  588. msr->data = data;
  589. return ret;
  590. }
  591. static void crash_vmclear_local_loaded_vmcss(void)
  592. {
  593. int cpu = raw_smp_processor_id();
  594. struct loaded_vmcs *v;
  595. list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
  596. loaded_vmcss_on_cpu_link)
  597. vmcs_clear(v->vmcs);
  598. }
  599. static void __loaded_vmcs_clear(void *arg)
  600. {
  601. struct loaded_vmcs *loaded_vmcs = arg;
  602. int cpu = raw_smp_processor_id();
  603. if (loaded_vmcs->cpu != cpu)
  604. return; /* vcpu migration can race with cpu offline */
  605. if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
  606. per_cpu(current_vmcs, cpu) = NULL;
  607. vmcs_clear(loaded_vmcs->vmcs);
  608. if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
  609. vmcs_clear(loaded_vmcs->shadow_vmcs);
  610. list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
  611. /*
  612. * Ensure all writes to loaded_vmcs, including deleting it from its
  613. * current percpu list, complete before setting loaded_vmcs->cpu to
  614. * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
  615. * and add loaded_vmcs to its percpu list before it's deleted from this
  616. * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
  617. */
  618. smp_wmb();
  619. loaded_vmcs->cpu = -1;
  620. loaded_vmcs->launched = 0;
  621. }
  622. void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
  623. {
  624. int cpu = loaded_vmcs->cpu;
  625. if (cpu != -1)
  626. smp_call_function_single(cpu,
  627. __loaded_vmcs_clear, loaded_vmcs, 1);
  628. }
  629. static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
  630. unsigned field)
  631. {
  632. bool ret;
  633. u32 mask = 1 << (seg * SEG_FIELD_NR + field);
  634. if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
  635. kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
  636. vmx->segment_cache.bitmask = 0;
  637. }
  638. ret = vmx->segment_cache.bitmask & mask;
  639. vmx->segment_cache.bitmask |= mask;
  640. return ret;
  641. }
  642. static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
  643. {
  644. u16 *p = &vmx->segment_cache.seg[seg].selector;
  645. if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
  646. *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
  647. return *p;
  648. }
  649. static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
  650. {
  651. ulong *p = &vmx->segment_cache.seg[seg].base;
  652. if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
  653. *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
  654. return *p;
  655. }
  656. static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
  657. {
  658. u32 *p = &vmx->segment_cache.seg[seg].limit;
  659. if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
  660. *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
  661. return *p;
  662. }
  663. static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
  664. {
  665. u32 *p = &vmx->segment_cache.seg[seg].ar;
  666. if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
  667. *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
  668. return *p;
  669. }
  670. void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
  671. {
  672. u32 eb;
  673. eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
  674. (1u << DB_VECTOR) | (1u << AC_VECTOR);
  675. /*
  676. * Guest access to VMware backdoor ports could legitimately
  677. * trigger #GP because of TSS I/O permission bitmap.
  678. * We intercept those #GP and allow access to them anyway
  679. * as VMware does.
  680. */
  681. if (enable_vmware_backdoor)
  682. eb |= (1u << GP_VECTOR);
  683. if ((vcpu->guest_debug &
  684. (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
  685. (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
  686. eb |= 1u << BP_VECTOR;
  687. if (to_vmx(vcpu)->rmode.vm86_active)
  688. eb = ~0;
  689. if (!vmx_need_pf_intercept(vcpu))
  690. eb &= ~(1u << PF_VECTOR);
  691. /* When we are running a nested L2 guest and L1 specified for it a
  692. * certain exception bitmap, we must trap the same exceptions and pass
  693. * them to L1. When running L2, we will only handle the exceptions
  694. * specified above if L1 did not want them.
  695. */
  696. if (is_guest_mode(vcpu))
  697. eb |= get_vmcs12(vcpu)->exception_bitmap;
  698. else {
  699. int mask = 0, match = 0;
  700. if (enable_ept && (eb & (1u << PF_VECTOR))) {
  701. /*
  702. * If EPT is enabled, #PF is currently only intercepted
  703. * if MAXPHYADDR is smaller on the guest than on the
  704. * host. In that case we only care about present,
  705. * non-reserved faults. For vmcs02, however, PFEC_MASK
  706. * and PFEC_MATCH are set in prepare_vmcs02_rare.
  707. */
  708. mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
  709. match = PFERR_PRESENT_MASK;
  710. }
  711. vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
  712. vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
  713. }
  714. /*
  715. * Disabling xfd interception indicates that dynamic xfeatures
  716. * might be used in the guest. Always trap #NM in this case
  717. * to save guest xfd_err timely.
  718. */
  719. if (vcpu->arch.xfd_no_write_intercept)
  720. eb |= (1u << NM_VECTOR);
  721. vmcs_write32(EXCEPTION_BITMAP, eb);
  722. }
  723. /*
  724. * Check if MSR is intercepted for currently loaded MSR bitmap.
  725. */
  726. static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
  727. {
  728. if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
  729. return true;
  730. return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
  731. }
  732. unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
  733. {
  734. unsigned int flags = 0;
  735. if (vmx->loaded_vmcs->launched)
  736. flags |= VMX_RUN_VMRESUME;
  737. /*
  738. * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
  739. * to change it directly without causing a vmexit. In that case read
  740. * it after vmexit and store it in vmx->spec_ctrl.
  741. */
  742. if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
  743. flags |= VMX_RUN_SAVE_SPEC_CTRL;
  744. return flags;
  745. }
  746. static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
  747. unsigned long entry, unsigned long exit)
  748. {
  749. vm_entry_controls_clearbit(vmx, entry);
  750. vm_exit_controls_clearbit(vmx, exit);
  751. }
  752. int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
  753. {
  754. unsigned int i;
  755. for (i = 0; i < m->nr; ++i) {
  756. if (m->val[i].index == msr)
  757. return i;
  758. }
  759. return -ENOENT;
  760. }
  761. static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
  762. {
  763. int i;
  764. struct msr_autoload *m = &vmx->msr_autoload;
  765. switch (msr) {
  766. case MSR_EFER:
  767. if (cpu_has_load_ia32_efer()) {
  768. clear_atomic_switch_msr_special(vmx,
  769. VM_ENTRY_LOAD_IA32_EFER,
  770. VM_EXIT_LOAD_IA32_EFER);
  771. return;
  772. }
  773. break;
  774. case MSR_CORE_PERF_GLOBAL_CTRL:
  775. if (cpu_has_load_perf_global_ctrl()) {
  776. clear_atomic_switch_msr_special(vmx,
  777. VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
  778. VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
  779. return;
  780. }
  781. break;
  782. }
  783. i = vmx_find_loadstore_msr_slot(&m->guest, msr);
  784. if (i < 0)
  785. goto skip_guest;
  786. --m->guest.nr;
  787. m->guest.val[i] = m->guest.val[m->guest.nr];
  788. vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
  789. skip_guest:
  790. i = vmx_find_loadstore_msr_slot(&m->host, msr);
  791. if (i < 0)
  792. return;
  793. --m->host.nr;
  794. m->host.val[i] = m->host.val[m->host.nr];
  795. vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
  796. }
  797. static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
  798. unsigned long entry, unsigned long exit,
  799. unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
  800. u64 guest_val, u64 host_val)
  801. {
  802. vmcs_write64(guest_val_vmcs, guest_val);
  803. if (host_val_vmcs != HOST_IA32_EFER)
  804. vmcs_write64(host_val_vmcs, host_val);
  805. vm_entry_controls_setbit(vmx, entry);
  806. vm_exit_controls_setbit(vmx, exit);
  807. }
  808. static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
  809. u64 guest_val, u64 host_val, bool entry_only)
  810. {
  811. int i, j = 0;
  812. struct msr_autoload *m = &vmx->msr_autoload;
  813. switch (msr) {
  814. case MSR_EFER:
  815. if (cpu_has_load_ia32_efer()) {
  816. add_atomic_switch_msr_special(vmx,
  817. VM_ENTRY_LOAD_IA32_EFER,
  818. VM_EXIT_LOAD_IA32_EFER,
  819. GUEST_IA32_EFER,
  820. HOST_IA32_EFER,
  821. guest_val, host_val);
  822. return;
  823. }
  824. break;
  825. case MSR_CORE_PERF_GLOBAL_CTRL:
  826. if (cpu_has_load_perf_global_ctrl()) {
  827. add_atomic_switch_msr_special(vmx,
  828. VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
  829. VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
  830. GUEST_IA32_PERF_GLOBAL_CTRL,
  831. HOST_IA32_PERF_GLOBAL_CTRL,
  832. guest_val, host_val);
  833. return;
  834. }
  835. break;
  836. case MSR_IA32_PEBS_ENABLE:
  837. /* PEBS needs a quiescent period after being disabled (to write
  838. * a record). Disabling PEBS through VMX MSR swapping doesn't
  839. * provide that period, so a CPU could write host's record into
  840. * guest's memory.
  841. */
  842. wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
  843. }
  844. i = vmx_find_loadstore_msr_slot(&m->guest, msr);
  845. if (!entry_only)
  846. j = vmx_find_loadstore_msr_slot(&m->host, msr);
  847. if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
  848. (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
  849. printk_once(KERN_WARNING "Not enough msr switch entries. "
  850. "Can't add msr %x\n", msr);
  851. return;
  852. }
  853. if (i < 0) {
  854. i = m->guest.nr++;
  855. vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
  856. }
  857. m->guest.val[i].index = msr;
  858. m->guest.val[i].value = guest_val;
  859. if (entry_only)
  860. return;
  861. if (j < 0) {
  862. j = m->host.nr++;
  863. vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
  864. }
  865. m->host.val[j].index = msr;
  866. m->host.val[j].value = host_val;
  867. }
  868. static bool update_transition_efer(struct vcpu_vmx *vmx)
  869. {
  870. u64 guest_efer = vmx->vcpu.arch.efer;
  871. u64 ignore_bits = 0;
  872. int i;
  873. /* Shadow paging assumes NX to be available. */
  874. if (!enable_ept)
  875. guest_efer |= EFER_NX;
  876. /*
  877. * LMA and LME handled by hardware; SCE meaningless outside long mode.
  878. */
  879. ignore_bits |= EFER_SCE;
  880. #ifdef CONFIG_X86_64
  881. ignore_bits |= EFER_LMA | EFER_LME;
  882. /* SCE is meaningful only in long mode on Intel */
  883. if (guest_efer & EFER_LMA)
  884. ignore_bits &= ~(u64)EFER_SCE;
  885. #endif
  886. /*
  887. * On EPT, we can't emulate NX, so we must switch EFER atomically.
  888. * On CPUs that support "load IA32_EFER", always switch EFER
  889. * atomically, since it's faster than switching it manually.
  890. */
  891. if (cpu_has_load_ia32_efer() ||
  892. (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
  893. if (!(guest_efer & EFER_LMA))
  894. guest_efer &= ~EFER_LME;
  895. if (guest_efer != host_efer)
  896. add_atomic_switch_msr(vmx, MSR_EFER,
  897. guest_efer, host_efer, false);
  898. else
  899. clear_atomic_switch_msr(vmx, MSR_EFER);
  900. return false;
  901. }
  902. i = kvm_find_user_return_msr(MSR_EFER);
  903. if (i < 0)
  904. return false;
  905. clear_atomic_switch_msr(vmx, MSR_EFER);
  906. guest_efer &= ~ignore_bits;
  907. guest_efer |= host_efer & ignore_bits;
  908. vmx->guest_uret_msrs[i].data = guest_efer;
  909. vmx->guest_uret_msrs[i].mask = ~ignore_bits;
  910. return true;
  911. }
  912. #ifdef CONFIG_X86_32
  913. /*
  914. * On 32-bit kernels, VM exits still load the FS and GS bases from the
  915. * VMCS rather than the segment table. KVM uses this helper to figure
  916. * out the current bases to poke them into the VMCS before entry.
  917. */
  918. static unsigned long segment_base(u16 selector)
  919. {
  920. struct desc_struct *table;
  921. unsigned long v;
  922. if (!(selector & ~SEGMENT_RPL_MASK))
  923. return 0;
  924. table = get_current_gdt_ro();
  925. if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
  926. u16 ldt_selector = kvm_read_ldt();
  927. if (!(ldt_selector & ~SEGMENT_RPL_MASK))
  928. return 0;
  929. table = (struct desc_struct *)segment_base(ldt_selector);
  930. }
  931. v = get_desc_base(&table[selector >> 3]);
  932. return v;
  933. }
  934. #endif
  935. static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
  936. {
  937. return vmx_pt_mode_is_host_guest() &&
  938. !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
  939. }
  940. static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
  941. {
  942. /* The base must be 128-byte aligned and a legal physical address. */
  943. return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
  944. }
  945. static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
  946. {
  947. u32 i;
  948. wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
  949. wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
  950. wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
  951. wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
  952. for (i = 0; i < addr_range; i++) {
  953. wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
  954. wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
  955. }
  956. }
  957. static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
  958. {
  959. u32 i;
  960. rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
  961. rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
  962. rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
  963. rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
  964. for (i = 0; i < addr_range; i++) {
  965. rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
  966. rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
  967. }
  968. }
  969. static void pt_guest_enter(struct vcpu_vmx *vmx)
  970. {
  971. if (vmx_pt_mode_is_system())
  972. return;
  973. /*
  974. * GUEST_IA32_RTIT_CTL is already set in the VMCS.
  975. * Save host state before VM entry.
  976. */
  977. rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
  978. if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
  979. wrmsrl(MSR_IA32_RTIT_CTL, 0);
  980. pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
  981. pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
  982. }
  983. }
  984. static void pt_guest_exit(struct vcpu_vmx *vmx)
  985. {
  986. if (vmx_pt_mode_is_system())
  987. return;
  988. if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
  989. pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
  990. pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
  991. }
  992. /*
  993. * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
  994. * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
  995. */
  996. if (vmx->pt_desc.host.ctl)
  997. wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
  998. }
  999. void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
  1000. unsigned long fs_base, unsigned long gs_base)
  1001. {
  1002. if (unlikely(fs_sel != host->fs_sel)) {
  1003. if (!(fs_sel & 7))
  1004. vmcs_write16(HOST_FS_SELECTOR, fs_sel);
  1005. else
  1006. vmcs_write16(HOST_FS_SELECTOR, 0);
  1007. host->fs_sel = fs_sel;
  1008. }
  1009. if (unlikely(gs_sel != host->gs_sel)) {
  1010. if (!(gs_sel & 7))
  1011. vmcs_write16(HOST_GS_SELECTOR, gs_sel);
  1012. else
  1013. vmcs_write16(HOST_GS_SELECTOR, 0);
  1014. host->gs_sel = gs_sel;
  1015. }
  1016. if (unlikely(fs_base != host->fs_base)) {
  1017. vmcs_writel(HOST_FS_BASE, fs_base);
  1018. host->fs_base = fs_base;
  1019. }
  1020. if (unlikely(gs_base != host->gs_base)) {
  1021. vmcs_writel(HOST_GS_BASE, gs_base);
  1022. host->gs_base = gs_base;
  1023. }
  1024. }
  1025. void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
  1026. {
  1027. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1028. struct vmcs_host_state *host_state;
  1029. #ifdef CONFIG_X86_64
  1030. int cpu = raw_smp_processor_id();
  1031. #endif
  1032. unsigned long fs_base, gs_base;
  1033. u16 fs_sel, gs_sel;
  1034. int i;
  1035. vmx->req_immediate_exit = false;
  1036. /*
  1037. * Note that guest MSRs to be saved/restored can also be changed
  1038. * when guest state is loaded. This happens when guest transitions
  1039. * to/from long-mode by setting MSR_EFER.LMA.
  1040. */
  1041. if (!vmx->guest_uret_msrs_loaded) {
  1042. vmx->guest_uret_msrs_loaded = true;
  1043. for (i = 0; i < kvm_nr_uret_msrs; ++i) {
  1044. if (!vmx->guest_uret_msrs[i].load_into_hardware)
  1045. continue;
  1046. kvm_set_user_return_msr(i,
  1047. vmx->guest_uret_msrs[i].data,
  1048. vmx->guest_uret_msrs[i].mask);
  1049. }
  1050. }
  1051. if (vmx->nested.need_vmcs12_to_shadow_sync)
  1052. nested_sync_vmcs12_to_shadow(vcpu);
  1053. if (vmx->guest_state_loaded)
  1054. return;
  1055. host_state = &vmx->loaded_vmcs->host_state;
  1056. /*
  1057. * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
  1058. * allow segment selectors with cpl > 0 or ti == 1.
  1059. */
  1060. host_state->ldt_sel = kvm_read_ldt();
  1061. #ifdef CONFIG_X86_64
  1062. savesegment(ds, host_state->ds_sel);
  1063. savesegment(es, host_state->es_sel);
  1064. gs_base = cpu_kernelmode_gs_base(cpu);
  1065. if (likely(is_64bit_mm(current->mm))) {
  1066. current_save_fsgs();
  1067. fs_sel = current->thread.fsindex;
  1068. gs_sel = current->thread.gsindex;
  1069. fs_base = current->thread.fsbase;
  1070. vmx->msr_host_kernel_gs_base = current->thread.gsbase;
  1071. } else {
  1072. savesegment(fs, fs_sel);
  1073. savesegment(gs, gs_sel);
  1074. fs_base = read_msr(MSR_FS_BASE);
  1075. vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
  1076. }
  1077. wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
  1078. #else
  1079. savesegment(fs, fs_sel);
  1080. savesegment(gs, gs_sel);
  1081. fs_base = segment_base(fs_sel);
  1082. gs_base = segment_base(gs_sel);
  1083. #endif
  1084. vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
  1085. vmx->guest_state_loaded = true;
  1086. }
  1087. static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
  1088. {
  1089. struct vmcs_host_state *host_state;
  1090. if (!vmx->guest_state_loaded)
  1091. return;
  1092. host_state = &vmx->loaded_vmcs->host_state;
  1093. ++vmx->vcpu.stat.host_state_reload;
  1094. #ifdef CONFIG_X86_64
  1095. rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
  1096. #endif
  1097. if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
  1098. kvm_load_ldt(host_state->ldt_sel);
  1099. #ifdef CONFIG_X86_64
  1100. load_gs_index(host_state->gs_sel);
  1101. #else
  1102. loadsegment(gs, host_state->gs_sel);
  1103. #endif
  1104. }
  1105. if (host_state->fs_sel & 7)
  1106. loadsegment(fs, host_state->fs_sel);
  1107. #ifdef CONFIG_X86_64
  1108. if (unlikely(host_state->ds_sel | host_state->es_sel)) {
  1109. loadsegment(ds, host_state->ds_sel);
  1110. loadsegment(es, host_state->es_sel);
  1111. }
  1112. #endif
  1113. invalidate_tss_limit();
  1114. #ifdef CONFIG_X86_64
  1115. wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
  1116. #endif
  1117. load_fixmap_gdt(raw_smp_processor_id());
  1118. vmx->guest_state_loaded = false;
  1119. vmx->guest_uret_msrs_loaded = false;
  1120. }
  1121. #ifdef CONFIG_X86_64
  1122. static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
  1123. {
  1124. preempt_disable();
  1125. if (vmx->guest_state_loaded)
  1126. rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
  1127. preempt_enable();
  1128. return vmx->msr_guest_kernel_gs_base;
  1129. }
  1130. static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
  1131. {
  1132. preempt_disable();
  1133. if (vmx->guest_state_loaded)
  1134. wrmsrl(MSR_KERNEL_GS_BASE, data);
  1135. preempt_enable();
  1136. vmx->msr_guest_kernel_gs_base = data;
  1137. }
  1138. #endif
  1139. void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
  1140. struct loaded_vmcs *buddy)
  1141. {
  1142. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1143. bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
  1144. struct vmcs *prev;
  1145. if (!already_loaded) {
  1146. loaded_vmcs_clear(vmx->loaded_vmcs);
  1147. local_irq_disable();
  1148. /*
  1149. * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
  1150. * this cpu's percpu list, otherwise it may not yet be deleted
  1151. * from its previous cpu's percpu list. Pairs with the
  1152. * smb_wmb() in __loaded_vmcs_clear().
  1153. */
  1154. smp_rmb();
  1155. list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
  1156. &per_cpu(loaded_vmcss_on_cpu, cpu));
  1157. local_irq_enable();
  1158. }
  1159. prev = per_cpu(current_vmcs, cpu);
  1160. if (prev != vmx->loaded_vmcs->vmcs) {
  1161. per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
  1162. vmcs_load(vmx->loaded_vmcs->vmcs);
  1163. /*
  1164. * No indirect branch prediction barrier needed when switching
  1165. * the active VMCS within a vCPU, unless IBRS is advertised to
  1166. * the vCPU. To minimize the number of IBPBs executed, KVM
  1167. * performs IBPB on nested VM-Exit (a single nested transition
  1168. * may switch the active VMCS multiple times).
  1169. */
  1170. if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
  1171. indirect_branch_prediction_barrier();
  1172. }
  1173. if (!already_loaded) {
  1174. void *gdt = get_current_gdt_ro();
  1175. /*
  1176. * Flush all EPTP/VPID contexts, the new pCPU may have stale
  1177. * TLB entries from its previous association with the vCPU.
  1178. */
  1179. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  1180. /*
  1181. * Linux uses per-cpu TSS and GDT, so set these when switching
  1182. * processors. See 22.2.4.
  1183. */
  1184. vmcs_writel(HOST_TR_BASE,
  1185. (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
  1186. vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
  1187. if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
  1188. /* 22.2.3 */
  1189. vmcs_writel(HOST_IA32_SYSENTER_ESP,
  1190. (unsigned long)(cpu_entry_stack(cpu) + 1));
  1191. }
  1192. vmx->loaded_vmcs->cpu = cpu;
  1193. }
  1194. }
  1195. /*
  1196. * Switches to specified vcpu, until a matching vcpu_put(), but assumes
  1197. * vcpu mutex is already taken.
  1198. */
  1199. static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  1200. {
  1201. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1202. vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
  1203. vmx_vcpu_pi_load(vcpu, cpu);
  1204. vmx->host_debugctlmsr = get_debugctlmsr();
  1205. }
  1206. static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
  1207. {
  1208. vmx_vcpu_pi_put(vcpu);
  1209. vmx_prepare_switch_to_host(to_vmx(vcpu));
  1210. }
  1211. bool vmx_emulation_required(struct kvm_vcpu *vcpu)
  1212. {
  1213. return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
  1214. }
  1215. unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
  1216. {
  1217. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1218. unsigned long rflags, save_rflags;
  1219. if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
  1220. kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
  1221. rflags = vmcs_readl(GUEST_RFLAGS);
  1222. if (vmx->rmode.vm86_active) {
  1223. rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
  1224. save_rflags = vmx->rmode.save_rflags;
  1225. rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
  1226. }
  1227. vmx->rflags = rflags;
  1228. }
  1229. return vmx->rflags;
  1230. }
  1231. void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  1232. {
  1233. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1234. unsigned long old_rflags;
  1235. /*
  1236. * Unlike CR0 and CR4, RFLAGS handling requires checking if the vCPU
  1237. * is an unrestricted guest in order to mark L2 as needing emulation
  1238. * if L1 runs L2 as a restricted guest.
  1239. */
  1240. if (is_unrestricted_guest(vcpu)) {
  1241. kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
  1242. vmx->rflags = rflags;
  1243. vmcs_writel(GUEST_RFLAGS, rflags);
  1244. return;
  1245. }
  1246. old_rflags = vmx_get_rflags(vcpu);
  1247. vmx->rflags = rflags;
  1248. if (vmx->rmode.vm86_active) {
  1249. vmx->rmode.save_rflags = rflags;
  1250. rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
  1251. }
  1252. vmcs_writel(GUEST_RFLAGS, rflags);
  1253. if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
  1254. vmx->emulation_required = vmx_emulation_required(vcpu);
  1255. }
  1256. static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
  1257. {
  1258. return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
  1259. }
  1260. u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
  1261. {
  1262. u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
  1263. int ret = 0;
  1264. if (interruptibility & GUEST_INTR_STATE_STI)
  1265. ret |= KVM_X86_SHADOW_INT_STI;
  1266. if (interruptibility & GUEST_INTR_STATE_MOV_SS)
  1267. ret |= KVM_X86_SHADOW_INT_MOV_SS;
  1268. return ret;
  1269. }
  1270. void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
  1271. {
  1272. u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
  1273. u32 interruptibility = interruptibility_old;
  1274. interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
  1275. if (mask & KVM_X86_SHADOW_INT_MOV_SS)
  1276. interruptibility |= GUEST_INTR_STATE_MOV_SS;
  1277. else if (mask & KVM_X86_SHADOW_INT_STI)
  1278. interruptibility |= GUEST_INTR_STATE_STI;
  1279. if ((interruptibility != interruptibility_old))
  1280. vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
  1281. }
  1282. static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
  1283. {
  1284. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1285. unsigned long value;
  1286. /*
  1287. * Any MSR write that attempts to change bits marked reserved will
  1288. * case a #GP fault.
  1289. */
  1290. if (data & vmx->pt_desc.ctl_bitmask)
  1291. return 1;
  1292. /*
  1293. * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
  1294. * result in a #GP unless the same write also clears TraceEn.
  1295. */
  1296. if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
  1297. ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
  1298. return 1;
  1299. /*
  1300. * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
  1301. * and FabricEn would cause #GP, if
  1302. * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
  1303. */
  1304. if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
  1305. !(data & RTIT_CTL_FABRIC_EN) &&
  1306. !intel_pt_validate_cap(vmx->pt_desc.caps,
  1307. PT_CAP_single_range_output))
  1308. return 1;
  1309. /*
  1310. * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
  1311. * utilize encodings marked reserved will cause a #GP fault.
  1312. */
  1313. value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
  1314. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
  1315. !test_bit((data & RTIT_CTL_MTC_RANGE) >>
  1316. RTIT_CTL_MTC_RANGE_OFFSET, &value))
  1317. return 1;
  1318. value = intel_pt_validate_cap(vmx->pt_desc.caps,
  1319. PT_CAP_cycle_thresholds);
  1320. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
  1321. !test_bit((data & RTIT_CTL_CYC_THRESH) >>
  1322. RTIT_CTL_CYC_THRESH_OFFSET, &value))
  1323. return 1;
  1324. value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
  1325. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
  1326. !test_bit((data & RTIT_CTL_PSB_FREQ) >>
  1327. RTIT_CTL_PSB_FREQ_OFFSET, &value))
  1328. return 1;
  1329. /*
  1330. * If ADDRx_CFG is reserved or the encodings is >2 will
  1331. * cause a #GP fault.
  1332. */
  1333. value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
  1334. if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
  1335. return 1;
  1336. value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
  1337. if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
  1338. return 1;
  1339. value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
  1340. if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
  1341. return 1;
  1342. value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
  1343. if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
  1344. return 1;
  1345. return 0;
  1346. }
  1347. static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
  1348. void *insn, int insn_len)
  1349. {
  1350. /*
  1351. * Emulation of instructions in SGX enclaves is impossible as RIP does
  1352. * not point at the failing instruction, and even if it did, the code
  1353. * stream is inaccessible. Inject #UD instead of exiting to userspace
  1354. * so that guest userspace can't DoS the guest simply by triggering
  1355. * emulation (enclaves are CPL3 only).
  1356. */
  1357. if (to_vmx(vcpu)->exit_reason.enclave_mode) {
  1358. kvm_queue_exception(vcpu, UD_VECTOR);
  1359. return false;
  1360. }
  1361. return true;
  1362. }
  1363. static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
  1364. {
  1365. union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
  1366. unsigned long rip, orig_rip;
  1367. u32 instr_len;
  1368. /*
  1369. * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
  1370. * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
  1371. * set when EPT misconfig occurs. In practice, real hardware updates
  1372. * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
  1373. * (namely Hyper-V) don't set it due to it being undefined behavior,
  1374. * i.e. we end up advancing IP with some random value.
  1375. */
  1376. if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
  1377. exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
  1378. instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
  1379. /*
  1380. * Emulating an enclave's instructions isn't supported as KVM
  1381. * cannot access the enclave's memory or its true RIP, e.g. the
  1382. * vmcs.GUEST_RIP points at the exit point of the enclave, not
  1383. * the RIP that actually triggered the VM-Exit. But, because
  1384. * most instructions that cause VM-Exit will #UD in an enclave,
  1385. * most instruction-based VM-Exits simply do not occur.
  1386. *
  1387. * There are a few exceptions, notably the debug instructions
  1388. * INT1ICEBRK and INT3, as they are allowed in debug enclaves
  1389. * and generate #DB/#BP as expected, which KVM might intercept.
  1390. * But again, the CPU does the dirty work and saves an instr
  1391. * length of zero so VMMs don't shoot themselves in the foot.
  1392. * WARN if KVM tries to skip a non-zero length instruction on
  1393. * a VM-Exit from an enclave.
  1394. */
  1395. if (!instr_len)
  1396. goto rip_updated;
  1397. WARN(exit_reason.enclave_mode,
  1398. "KVM: skipping instruction after SGX enclave VM-Exit");
  1399. orig_rip = kvm_rip_read(vcpu);
  1400. rip = orig_rip + instr_len;
  1401. #ifdef CONFIG_X86_64
  1402. /*
  1403. * We need to mask out the high 32 bits of RIP if not in 64-bit
  1404. * mode, but just finding out that we are in 64-bit mode is
  1405. * quite expensive. Only do it if there was a carry.
  1406. */
  1407. if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
  1408. rip = (u32)rip;
  1409. #endif
  1410. kvm_rip_write(vcpu, rip);
  1411. } else {
  1412. if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
  1413. return 0;
  1414. }
  1415. rip_updated:
  1416. /* skipping an emulated instruction also counts */
  1417. vmx_set_interrupt_shadow(vcpu, 0);
  1418. return 1;
  1419. }
  1420. /*
  1421. * Recognizes a pending MTF VM-exit and records the nested state for later
  1422. * delivery.
  1423. */
  1424. static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
  1425. {
  1426. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  1427. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1428. if (!is_guest_mode(vcpu))
  1429. return;
  1430. /*
  1431. * Per the SDM, MTF takes priority over debug-trap exceptions besides
  1432. * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps
  1433. * or ICEBP (in the emulator proper), and skipping of ICEBP after an
  1434. * intercepted #DB deliberately avoids single-step #DB and MTF updates
  1435. * as ICEBP is higher priority than both. As instruction emulation is
  1436. * completed at this point (i.e. KVM is at the instruction boundary),
  1437. * any #DB exception pending delivery must be a debug-trap of lower
  1438. * priority than MTF. Record the pending MTF state to be delivered in
  1439. * vmx_check_nested_events().
  1440. */
  1441. if (nested_cpu_has_mtf(vmcs12) &&
  1442. (!vcpu->arch.exception.pending ||
  1443. vcpu->arch.exception.vector == DB_VECTOR) &&
  1444. (!vcpu->arch.exception_vmexit.pending ||
  1445. vcpu->arch.exception_vmexit.vector == DB_VECTOR)) {
  1446. vmx->nested.mtf_pending = true;
  1447. kvm_make_request(KVM_REQ_EVENT, vcpu);
  1448. } else {
  1449. vmx->nested.mtf_pending = false;
  1450. }
  1451. }
  1452. static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  1453. {
  1454. vmx_update_emulated_instruction(vcpu);
  1455. return skip_emulated_instruction(vcpu);
  1456. }
  1457. static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
  1458. {
  1459. /*
  1460. * Ensure that we clear the HLT state in the VMCS. We don't need to
  1461. * explicitly skip the instruction because if the HLT state is set,
  1462. * then the instruction is already executing and RIP has already been
  1463. * advanced.
  1464. */
  1465. if (kvm_hlt_in_guest(vcpu->kvm) &&
  1466. vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
  1467. vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
  1468. }
  1469. static void vmx_inject_exception(struct kvm_vcpu *vcpu)
  1470. {
  1471. struct kvm_queued_exception *ex = &vcpu->arch.exception;
  1472. u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
  1473. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1474. kvm_deliver_exception_payload(vcpu, ex);
  1475. if (ex->has_error_code) {
  1476. /*
  1477. * Despite the error code being architecturally defined as 32
  1478. * bits, and the VMCS field being 32 bits, Intel CPUs and thus
  1479. * VMX don't actually supporting setting bits 31:16. Hardware
  1480. * will (should) never provide a bogus error code, but AMD CPUs
  1481. * do generate error codes with bits 31:16 set, and so KVM's
  1482. * ABI lets userspace shove in arbitrary 32-bit values. Drop
  1483. * the upper bits to avoid VM-Fail, losing information that
  1484. * does't really exist is preferable to killing the VM.
  1485. */
  1486. vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
  1487. intr_info |= INTR_INFO_DELIVER_CODE_MASK;
  1488. }
  1489. if (vmx->rmode.vm86_active) {
  1490. int inc_eip = 0;
  1491. if (kvm_exception_is_soft(ex->vector))
  1492. inc_eip = vcpu->arch.event_exit_inst_len;
  1493. kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
  1494. return;
  1495. }
  1496. WARN_ON_ONCE(vmx->emulation_required);
  1497. if (kvm_exception_is_soft(ex->vector)) {
  1498. vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
  1499. vmx->vcpu.arch.event_exit_inst_len);
  1500. intr_info |= INTR_TYPE_SOFT_EXCEPTION;
  1501. } else
  1502. intr_info |= INTR_TYPE_HARD_EXCEPTION;
  1503. vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
  1504. vmx_clear_hlt(vcpu);
  1505. }
  1506. static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
  1507. bool load_into_hardware)
  1508. {
  1509. struct vmx_uret_msr *uret_msr;
  1510. uret_msr = vmx_find_uret_msr(vmx, msr);
  1511. if (!uret_msr)
  1512. return;
  1513. uret_msr->load_into_hardware = load_into_hardware;
  1514. }
  1515. /*
  1516. * Configuring user return MSRs to automatically save, load, and restore MSRs
  1517. * that need to be shoved into hardware when running the guest. Note, omitting
  1518. * an MSR here does _NOT_ mean it's not emulated, only that it will not be
  1519. * loaded into hardware when running the guest.
  1520. */
  1521. static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
  1522. {
  1523. #ifdef CONFIG_X86_64
  1524. bool load_syscall_msrs;
  1525. /*
  1526. * The SYSCALL MSRs are only needed on long mode guests, and only
  1527. * when EFER.SCE is set.
  1528. */
  1529. load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
  1530. (vmx->vcpu.arch.efer & EFER_SCE);
  1531. vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
  1532. vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
  1533. vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
  1534. #endif
  1535. vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
  1536. vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
  1537. guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
  1538. guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
  1539. /*
  1540. * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
  1541. * kernel and old userspace. If those guests run on a tsx=off host, do
  1542. * allow guests to use TSX_CTRL, but don't change the value in hardware
  1543. * so that TSX remains always disabled.
  1544. */
  1545. vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
  1546. /*
  1547. * The set of MSRs to load may have changed, reload MSRs before the
  1548. * next VM-Enter.
  1549. */
  1550. vmx->guest_uret_msrs_loaded = false;
  1551. }
  1552. u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
  1553. {
  1554. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  1555. if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
  1556. return vmcs12->tsc_offset;
  1557. return 0;
  1558. }
  1559. u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
  1560. {
  1561. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  1562. if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
  1563. nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
  1564. return vmcs12->tsc_multiplier;
  1565. return kvm_caps.default_tsc_scaling_ratio;
  1566. }
  1567. static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
  1568. {
  1569. vmcs_write64(TSC_OFFSET, offset);
  1570. }
  1571. static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
  1572. {
  1573. vmcs_write64(TSC_MULTIPLIER, multiplier);
  1574. }
  1575. /*
  1576. * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
  1577. * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
  1578. * all guests if the "nested" module option is off, and can also be disabled
  1579. * for a single guest by disabling its VMX cpuid bit.
  1580. */
  1581. bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
  1582. {
  1583. return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
  1584. }
  1585. static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
  1586. uint64_t val)
  1587. {
  1588. uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
  1589. return !(val & ~valid_bits);
  1590. }
  1591. static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
  1592. {
  1593. switch (msr->index) {
  1594. case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
  1595. if (!nested)
  1596. return 1;
  1597. return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
  1598. case MSR_IA32_PERF_CAPABILITIES:
  1599. msr->data = kvm_caps.supported_perf_cap;
  1600. return 0;
  1601. default:
  1602. return KVM_MSR_RET_INVALID;
  1603. }
  1604. }
  1605. /*
  1606. * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
  1607. * Returns 0 on success, non-0 otherwise.
  1608. * Assumes vcpu_load() was already called.
  1609. */
  1610. static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1611. {
  1612. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1613. struct vmx_uret_msr *msr;
  1614. u32 index;
  1615. switch (msr_info->index) {
  1616. #ifdef CONFIG_X86_64
  1617. case MSR_FS_BASE:
  1618. msr_info->data = vmcs_readl(GUEST_FS_BASE);
  1619. break;
  1620. case MSR_GS_BASE:
  1621. msr_info->data = vmcs_readl(GUEST_GS_BASE);
  1622. break;
  1623. case MSR_KERNEL_GS_BASE:
  1624. msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
  1625. break;
  1626. #endif
  1627. case MSR_EFER:
  1628. return kvm_get_msr_common(vcpu, msr_info);
  1629. case MSR_IA32_TSX_CTRL:
  1630. if (!msr_info->host_initiated &&
  1631. !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
  1632. return 1;
  1633. goto find_uret_msr;
  1634. case MSR_IA32_UMWAIT_CONTROL:
  1635. if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
  1636. return 1;
  1637. msr_info->data = vmx->msr_ia32_umwait_control;
  1638. break;
  1639. case MSR_IA32_SPEC_CTRL:
  1640. if (!msr_info->host_initiated &&
  1641. !guest_has_spec_ctrl_msr(vcpu))
  1642. return 1;
  1643. msr_info->data = to_vmx(vcpu)->spec_ctrl;
  1644. break;
  1645. case MSR_IA32_SYSENTER_CS:
  1646. msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
  1647. break;
  1648. case MSR_IA32_SYSENTER_EIP:
  1649. msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
  1650. break;
  1651. case MSR_IA32_SYSENTER_ESP:
  1652. msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
  1653. break;
  1654. case MSR_IA32_BNDCFGS:
  1655. if (!kvm_mpx_supported() ||
  1656. (!msr_info->host_initiated &&
  1657. !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
  1658. return 1;
  1659. msr_info->data = vmcs_read64(GUEST_BNDCFGS);
  1660. break;
  1661. case MSR_IA32_MCG_EXT_CTL:
  1662. if (!msr_info->host_initiated &&
  1663. !(vmx->msr_ia32_feature_control &
  1664. FEAT_CTL_LMCE_ENABLED))
  1665. return 1;
  1666. msr_info->data = vcpu->arch.mcg_ext_ctl;
  1667. break;
  1668. case MSR_IA32_FEAT_CTL:
  1669. msr_info->data = vmx->msr_ia32_feature_control;
  1670. break;
  1671. case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
  1672. if (!msr_info->host_initiated &&
  1673. !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
  1674. return 1;
  1675. msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
  1676. [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
  1677. break;
  1678. case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
  1679. if (!nested_vmx_allowed(vcpu))
  1680. return 1;
  1681. if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
  1682. &msr_info->data))
  1683. return 1;
  1684. /*
  1685. * Enlightened VMCS v1 doesn't have certain VMCS fields but
  1686. * instead of just ignoring the features, different Hyper-V
  1687. * versions are either trying to use them and fail or do some
  1688. * sanity checking and refuse to boot. Filter all unsupported
  1689. * features out.
  1690. */
  1691. if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
  1692. nested_evmcs_filter_control_msr(vcpu, msr_info->index,
  1693. &msr_info->data);
  1694. break;
  1695. case MSR_IA32_RTIT_CTL:
  1696. if (!vmx_pt_mode_is_host_guest())
  1697. return 1;
  1698. msr_info->data = vmx->pt_desc.guest.ctl;
  1699. break;
  1700. case MSR_IA32_RTIT_STATUS:
  1701. if (!vmx_pt_mode_is_host_guest())
  1702. return 1;
  1703. msr_info->data = vmx->pt_desc.guest.status;
  1704. break;
  1705. case MSR_IA32_RTIT_CR3_MATCH:
  1706. if (!vmx_pt_mode_is_host_guest() ||
  1707. !intel_pt_validate_cap(vmx->pt_desc.caps,
  1708. PT_CAP_cr3_filtering))
  1709. return 1;
  1710. msr_info->data = vmx->pt_desc.guest.cr3_match;
  1711. break;
  1712. case MSR_IA32_RTIT_OUTPUT_BASE:
  1713. if (!vmx_pt_mode_is_host_guest() ||
  1714. (!intel_pt_validate_cap(vmx->pt_desc.caps,
  1715. PT_CAP_topa_output) &&
  1716. !intel_pt_validate_cap(vmx->pt_desc.caps,
  1717. PT_CAP_single_range_output)))
  1718. return 1;
  1719. msr_info->data = vmx->pt_desc.guest.output_base;
  1720. break;
  1721. case MSR_IA32_RTIT_OUTPUT_MASK:
  1722. if (!vmx_pt_mode_is_host_guest() ||
  1723. (!intel_pt_validate_cap(vmx->pt_desc.caps,
  1724. PT_CAP_topa_output) &&
  1725. !intel_pt_validate_cap(vmx->pt_desc.caps,
  1726. PT_CAP_single_range_output)))
  1727. return 1;
  1728. msr_info->data = vmx->pt_desc.guest.output_mask;
  1729. break;
  1730. case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
  1731. index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
  1732. if (!vmx_pt_mode_is_host_guest() ||
  1733. (index >= 2 * vmx->pt_desc.num_address_ranges))
  1734. return 1;
  1735. if (index % 2)
  1736. msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
  1737. else
  1738. msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
  1739. break;
  1740. case MSR_IA32_DEBUGCTLMSR:
  1741. msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
  1742. break;
  1743. default:
  1744. find_uret_msr:
  1745. msr = vmx_find_uret_msr(vmx, msr_info->index);
  1746. if (msr) {
  1747. msr_info->data = msr->data;
  1748. break;
  1749. }
  1750. return kvm_get_msr_common(vcpu, msr_info);
  1751. }
  1752. return 0;
  1753. }
  1754. static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
  1755. u64 data)
  1756. {
  1757. #ifdef CONFIG_X86_64
  1758. if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
  1759. return (u32)data;
  1760. #endif
  1761. return (unsigned long)data;
  1762. }
  1763. static u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated)
  1764. {
  1765. u64 debugctl = 0;
  1766. if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) &&
  1767. (host_initiated || guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT)))
  1768. debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT;
  1769. if ((kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT) &&
  1770. (host_initiated || intel_pmu_lbr_is_enabled(vcpu)))
  1771. debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI;
  1772. return debugctl;
  1773. }
  1774. /*
  1775. * Writes msr value into the appropriate "register".
  1776. * Returns 0 on success, non-0 otherwise.
  1777. * Assumes vcpu_load() was already called.
  1778. */
  1779. static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1780. {
  1781. struct vcpu_vmx *vmx = to_vmx(vcpu);
  1782. struct vmx_uret_msr *msr;
  1783. int ret = 0;
  1784. u32 msr_index = msr_info->index;
  1785. u64 data = msr_info->data;
  1786. u32 index;
  1787. switch (msr_index) {
  1788. case MSR_EFER:
  1789. ret = kvm_set_msr_common(vcpu, msr_info);
  1790. break;
  1791. #ifdef CONFIG_X86_64
  1792. case MSR_FS_BASE:
  1793. vmx_segment_cache_clear(vmx);
  1794. vmcs_writel(GUEST_FS_BASE, data);
  1795. break;
  1796. case MSR_GS_BASE:
  1797. vmx_segment_cache_clear(vmx);
  1798. vmcs_writel(GUEST_GS_BASE, data);
  1799. break;
  1800. case MSR_KERNEL_GS_BASE:
  1801. vmx_write_guest_kernel_gs_base(vmx, data);
  1802. break;
  1803. case MSR_IA32_XFD:
  1804. ret = kvm_set_msr_common(vcpu, msr_info);
  1805. /*
  1806. * Always intercepting WRMSR could incur non-negligible
  1807. * overhead given xfd might be changed frequently in
  1808. * guest context switch. Disable write interception
  1809. * upon the first write with a non-zero value (indicating
  1810. * potential usage on dynamic xfeatures). Also update
  1811. * exception bitmap to trap #NM for proper virtualization
  1812. * of guest xfd_err.
  1813. */
  1814. if (!ret && data) {
  1815. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
  1816. MSR_TYPE_RW);
  1817. vcpu->arch.xfd_no_write_intercept = true;
  1818. vmx_update_exception_bitmap(vcpu);
  1819. }
  1820. break;
  1821. #endif
  1822. case MSR_IA32_SYSENTER_CS:
  1823. if (is_guest_mode(vcpu))
  1824. get_vmcs12(vcpu)->guest_sysenter_cs = data;
  1825. vmcs_write32(GUEST_SYSENTER_CS, data);
  1826. break;
  1827. case MSR_IA32_SYSENTER_EIP:
  1828. if (is_guest_mode(vcpu)) {
  1829. data = nested_vmx_truncate_sysenter_addr(vcpu, data);
  1830. get_vmcs12(vcpu)->guest_sysenter_eip = data;
  1831. }
  1832. vmcs_writel(GUEST_SYSENTER_EIP, data);
  1833. break;
  1834. case MSR_IA32_SYSENTER_ESP:
  1835. if (is_guest_mode(vcpu)) {
  1836. data = nested_vmx_truncate_sysenter_addr(vcpu, data);
  1837. get_vmcs12(vcpu)->guest_sysenter_esp = data;
  1838. }
  1839. vmcs_writel(GUEST_SYSENTER_ESP, data);
  1840. break;
  1841. case MSR_IA32_DEBUGCTLMSR: {
  1842. u64 invalid;
  1843. invalid = data & ~vmx_get_supported_debugctl(vcpu, msr_info->host_initiated);
  1844. if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
  1845. if (report_ignored_msrs)
  1846. vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
  1847. __func__, data);
  1848. data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
  1849. invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
  1850. }
  1851. if (invalid)
  1852. return 1;
  1853. if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
  1854. VM_EXIT_SAVE_DEBUG_CONTROLS)
  1855. get_vmcs12(vcpu)->guest_ia32_debugctl = data;
  1856. vmcs_write64(GUEST_IA32_DEBUGCTL, data);
  1857. if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
  1858. (data & DEBUGCTLMSR_LBR))
  1859. intel_pmu_create_guest_lbr_event(vcpu);
  1860. return 0;
  1861. }
  1862. case MSR_IA32_BNDCFGS:
  1863. if (!kvm_mpx_supported() ||
  1864. (!msr_info->host_initiated &&
  1865. !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
  1866. return 1;
  1867. if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
  1868. (data & MSR_IA32_BNDCFGS_RSVD))
  1869. return 1;
  1870. if (is_guest_mode(vcpu) &&
  1871. ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
  1872. (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
  1873. get_vmcs12(vcpu)->guest_bndcfgs = data;
  1874. vmcs_write64(GUEST_BNDCFGS, data);
  1875. break;
  1876. case MSR_IA32_UMWAIT_CONTROL:
  1877. if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
  1878. return 1;
  1879. /* The reserved bit 1 and non-32 bit [63:32] should be zero */
  1880. if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
  1881. return 1;
  1882. vmx->msr_ia32_umwait_control = data;
  1883. break;
  1884. case MSR_IA32_SPEC_CTRL:
  1885. if (!msr_info->host_initiated &&
  1886. !guest_has_spec_ctrl_msr(vcpu))
  1887. return 1;
  1888. if (kvm_spec_ctrl_test_value(data))
  1889. return 1;
  1890. vmx->spec_ctrl = data;
  1891. if (!data)
  1892. break;
  1893. /*
  1894. * For non-nested:
  1895. * When it's written (to non-zero) for the first time, pass
  1896. * it through.
  1897. *
  1898. * For nested:
  1899. * The handling of the MSR bitmap for L2 guests is done in
  1900. * nested_vmx_prepare_msr_bitmap. We should not touch the
  1901. * vmcs02.msr_bitmap here since it gets completely overwritten
  1902. * in the merging. We update the vmcs01 here for L1 as well
  1903. * since it will end up touching the MSR anyway now.
  1904. */
  1905. vmx_disable_intercept_for_msr(vcpu,
  1906. MSR_IA32_SPEC_CTRL,
  1907. MSR_TYPE_RW);
  1908. break;
  1909. case MSR_IA32_TSX_CTRL:
  1910. if (!msr_info->host_initiated &&
  1911. !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
  1912. return 1;
  1913. if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
  1914. return 1;
  1915. goto find_uret_msr;
  1916. case MSR_IA32_PRED_CMD:
  1917. if (!msr_info->host_initiated &&
  1918. !guest_has_pred_cmd_msr(vcpu))
  1919. return 1;
  1920. if (data & ~PRED_CMD_IBPB)
  1921. return 1;
  1922. if (!boot_cpu_has(X86_FEATURE_IBPB))
  1923. return 1;
  1924. if (!data)
  1925. break;
  1926. wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
  1927. /*
  1928. * For non-nested:
  1929. * When it's written (to non-zero) for the first time, pass
  1930. * it through.
  1931. *
  1932. * For nested:
  1933. * The handling of the MSR bitmap for L2 guests is done in
  1934. * nested_vmx_prepare_msr_bitmap. We should not touch the
  1935. * vmcs02.msr_bitmap here since it gets completely overwritten
  1936. * in the merging.
  1937. */
  1938. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
  1939. break;
  1940. case MSR_IA32_CR_PAT:
  1941. if (!kvm_pat_valid(data))
  1942. return 1;
  1943. if (is_guest_mode(vcpu) &&
  1944. get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
  1945. get_vmcs12(vcpu)->guest_ia32_pat = data;
  1946. if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
  1947. vmcs_write64(GUEST_IA32_PAT, data);
  1948. vcpu->arch.pat = data;
  1949. break;
  1950. }
  1951. ret = kvm_set_msr_common(vcpu, msr_info);
  1952. break;
  1953. case MSR_IA32_MCG_EXT_CTL:
  1954. if ((!msr_info->host_initiated &&
  1955. !(to_vmx(vcpu)->msr_ia32_feature_control &
  1956. FEAT_CTL_LMCE_ENABLED)) ||
  1957. (data & ~MCG_EXT_CTL_LMCE_EN))
  1958. return 1;
  1959. vcpu->arch.mcg_ext_ctl = data;
  1960. break;
  1961. case MSR_IA32_FEAT_CTL:
  1962. if (!vmx_feature_control_msr_valid(vcpu, data) ||
  1963. (to_vmx(vcpu)->msr_ia32_feature_control &
  1964. FEAT_CTL_LOCKED && !msr_info->host_initiated))
  1965. return 1;
  1966. vmx->msr_ia32_feature_control = data;
  1967. if (msr_info->host_initiated && data == 0)
  1968. vmx_leave_nested(vcpu);
  1969. /* SGX may be enabled/disabled by guest's firmware */
  1970. vmx_write_encls_bitmap(vcpu, NULL);
  1971. break;
  1972. case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
  1973. /*
  1974. * On real hardware, the LE hash MSRs are writable before
  1975. * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
  1976. * at which point SGX related bits in IA32_FEATURE_CONTROL
  1977. * become writable.
  1978. *
  1979. * KVM does not emulate SGX activation for simplicity, so
  1980. * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
  1981. * is unlocked. This is technically not architectural
  1982. * behavior, but it's close enough.
  1983. */
  1984. if (!msr_info->host_initiated &&
  1985. (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
  1986. ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
  1987. !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
  1988. return 1;
  1989. vmx->msr_ia32_sgxlepubkeyhash
  1990. [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
  1991. break;
  1992. case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
  1993. if (!msr_info->host_initiated)
  1994. return 1; /* they are read-only */
  1995. if (!nested_vmx_allowed(vcpu))
  1996. return 1;
  1997. return vmx_set_vmx_msr(vcpu, msr_index, data);
  1998. case MSR_IA32_RTIT_CTL:
  1999. if (!vmx_pt_mode_is_host_guest() ||
  2000. vmx_rtit_ctl_check(vcpu, data) ||
  2001. vmx->nested.vmxon)
  2002. return 1;
  2003. vmcs_write64(GUEST_IA32_RTIT_CTL, data);
  2004. vmx->pt_desc.guest.ctl = data;
  2005. pt_update_intercept_for_msr(vcpu);
  2006. break;
  2007. case MSR_IA32_RTIT_STATUS:
  2008. if (!pt_can_write_msr(vmx))
  2009. return 1;
  2010. if (data & MSR_IA32_RTIT_STATUS_MASK)
  2011. return 1;
  2012. vmx->pt_desc.guest.status = data;
  2013. break;
  2014. case MSR_IA32_RTIT_CR3_MATCH:
  2015. if (!pt_can_write_msr(vmx))
  2016. return 1;
  2017. if (!intel_pt_validate_cap(vmx->pt_desc.caps,
  2018. PT_CAP_cr3_filtering))
  2019. return 1;
  2020. vmx->pt_desc.guest.cr3_match = data;
  2021. break;
  2022. case MSR_IA32_RTIT_OUTPUT_BASE:
  2023. if (!pt_can_write_msr(vmx))
  2024. return 1;
  2025. if (!intel_pt_validate_cap(vmx->pt_desc.caps,
  2026. PT_CAP_topa_output) &&
  2027. !intel_pt_validate_cap(vmx->pt_desc.caps,
  2028. PT_CAP_single_range_output))
  2029. return 1;
  2030. if (!pt_output_base_valid(vcpu, data))
  2031. return 1;
  2032. vmx->pt_desc.guest.output_base = data;
  2033. break;
  2034. case MSR_IA32_RTIT_OUTPUT_MASK:
  2035. if (!pt_can_write_msr(vmx))
  2036. return 1;
  2037. if (!intel_pt_validate_cap(vmx->pt_desc.caps,
  2038. PT_CAP_topa_output) &&
  2039. !intel_pt_validate_cap(vmx->pt_desc.caps,
  2040. PT_CAP_single_range_output))
  2041. return 1;
  2042. vmx->pt_desc.guest.output_mask = data;
  2043. break;
  2044. case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
  2045. if (!pt_can_write_msr(vmx))
  2046. return 1;
  2047. index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
  2048. if (index >= 2 * vmx->pt_desc.num_address_ranges)
  2049. return 1;
  2050. if (is_noncanonical_address(data, vcpu))
  2051. return 1;
  2052. if (index % 2)
  2053. vmx->pt_desc.guest.addr_b[index / 2] = data;
  2054. else
  2055. vmx->pt_desc.guest.addr_a[index / 2] = data;
  2056. break;
  2057. case MSR_IA32_PERF_CAPABILITIES:
  2058. if (data && !vcpu_to_pmu(vcpu)->version)
  2059. return 1;
  2060. if (data & PMU_CAP_LBR_FMT) {
  2061. if ((data & PMU_CAP_LBR_FMT) !=
  2062. (kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT))
  2063. return 1;
  2064. if (!cpuid_model_is_consistent(vcpu))
  2065. return 1;
  2066. }
  2067. if (data & PERF_CAP_PEBS_FORMAT) {
  2068. if ((data & PERF_CAP_PEBS_MASK) !=
  2069. (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK))
  2070. return 1;
  2071. if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
  2072. return 1;
  2073. if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
  2074. return 1;
  2075. if (!cpuid_model_is_consistent(vcpu))
  2076. return 1;
  2077. }
  2078. ret = kvm_set_msr_common(vcpu, msr_info);
  2079. break;
  2080. default:
  2081. find_uret_msr:
  2082. msr = vmx_find_uret_msr(vmx, msr_index);
  2083. if (msr)
  2084. ret = vmx_set_guest_uret_msr(vmx, msr, data);
  2085. else
  2086. ret = kvm_set_msr_common(vcpu, msr_info);
  2087. }
  2088. /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
  2089. if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
  2090. vmx_update_fb_clear_dis(vcpu, vmx);
  2091. return ret;
  2092. }
  2093. static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
  2094. {
  2095. unsigned long guest_owned_bits;
  2096. kvm_register_mark_available(vcpu, reg);
  2097. switch (reg) {
  2098. case VCPU_REGS_RSP:
  2099. vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
  2100. break;
  2101. case VCPU_REGS_RIP:
  2102. vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
  2103. break;
  2104. case VCPU_EXREG_PDPTR:
  2105. if (enable_ept)
  2106. ept_save_pdptrs(vcpu);
  2107. break;
  2108. case VCPU_EXREG_CR0:
  2109. guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
  2110. vcpu->arch.cr0 &= ~guest_owned_bits;
  2111. vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
  2112. break;
  2113. case VCPU_EXREG_CR3:
  2114. /*
  2115. * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
  2116. * CR3 is loaded into hardware, not the guest's CR3.
  2117. */
  2118. if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
  2119. vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
  2120. break;
  2121. case VCPU_EXREG_CR4:
  2122. guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
  2123. vcpu->arch.cr4 &= ~guest_owned_bits;
  2124. vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
  2125. break;
  2126. default:
  2127. KVM_BUG_ON(1, vcpu->kvm);
  2128. break;
  2129. }
  2130. }
  2131. static __init int cpu_has_kvm_support(void)
  2132. {
  2133. return cpu_has_vmx();
  2134. }
  2135. static __init int vmx_disabled_by_bios(void)
  2136. {
  2137. return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
  2138. !boot_cpu_has(X86_FEATURE_VMX);
  2139. }
  2140. static int kvm_cpu_vmxon(u64 vmxon_pointer)
  2141. {
  2142. u64 msr;
  2143. cr4_set_bits(X86_CR4_VMXE);
  2144. asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
  2145. _ASM_EXTABLE(1b, %l[fault])
  2146. : : [vmxon_pointer] "m"(vmxon_pointer)
  2147. : : fault);
  2148. return 0;
  2149. fault:
  2150. WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
  2151. rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
  2152. cr4_clear_bits(X86_CR4_VMXE);
  2153. return -EFAULT;
  2154. }
  2155. static int vmx_hardware_enable(void)
  2156. {
  2157. int cpu = raw_smp_processor_id();
  2158. u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
  2159. int r;
  2160. if (cr4_read_shadow() & X86_CR4_VMXE)
  2161. return -EBUSY;
  2162. /*
  2163. * This can happen if we hot-added a CPU but failed to allocate
  2164. * VP assist page for it.
  2165. */
  2166. if (static_branch_unlikely(&enable_evmcs) &&
  2167. !hv_get_vp_assist_page(cpu))
  2168. return -EFAULT;
  2169. intel_pt_handle_vmx(1);
  2170. r = kvm_cpu_vmxon(phys_addr);
  2171. if (r) {
  2172. intel_pt_handle_vmx(0);
  2173. return r;
  2174. }
  2175. if (enable_ept)
  2176. ept_sync_global();
  2177. return 0;
  2178. }
  2179. static void vmclear_local_loaded_vmcss(void)
  2180. {
  2181. int cpu = raw_smp_processor_id();
  2182. struct loaded_vmcs *v, *n;
  2183. list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
  2184. loaded_vmcss_on_cpu_link)
  2185. __loaded_vmcs_clear(v);
  2186. }
  2187. static void vmx_hardware_disable(void)
  2188. {
  2189. vmclear_local_loaded_vmcss();
  2190. if (cpu_vmxoff())
  2191. kvm_spurious_fault();
  2192. hv_reset_evmcs();
  2193. intel_pt_handle_vmx(0);
  2194. }
  2195. /*
  2196. * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
  2197. * directly instead of going through cpu_has(), to ensure KVM is trapping
  2198. * ENCLS whenever it's supported in hardware. It does not matter whether
  2199. * the host OS supports or has enabled SGX.
  2200. */
  2201. static bool cpu_has_sgx(void)
  2202. {
  2203. return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
  2204. }
  2205. /*
  2206. * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
  2207. * can't be used due to errata where VM Exit may incorrectly clear
  2208. * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
  2209. * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
  2210. */
  2211. static bool cpu_has_perf_global_ctrl_bug(void)
  2212. {
  2213. if (boot_cpu_data.x86 == 0x6) {
  2214. switch (boot_cpu_data.x86_model) {
  2215. case INTEL_FAM6_NEHALEM_EP: /* AAK155 */
  2216. case INTEL_FAM6_NEHALEM: /* AAP115 */
  2217. case INTEL_FAM6_WESTMERE: /* AAT100 */
  2218. case INTEL_FAM6_WESTMERE_EP: /* BC86,AAY89,BD102 */
  2219. case INTEL_FAM6_NEHALEM_EX: /* BA97 */
  2220. return true;
  2221. default:
  2222. break;
  2223. }
  2224. }
  2225. return false;
  2226. }
  2227. static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
  2228. u32 msr, u32 *result)
  2229. {
  2230. u32 vmx_msr_low, vmx_msr_high;
  2231. u32 ctl = ctl_min | ctl_opt;
  2232. rdmsr(msr, vmx_msr_low, vmx_msr_high);
  2233. ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
  2234. ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
  2235. /* Ensure minimum (required) set of control bits are supported. */
  2236. if (ctl_min & ~ctl)
  2237. return -EIO;
  2238. *result = ctl;
  2239. return 0;
  2240. }
  2241. static __init u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
  2242. {
  2243. u64 allowed;
  2244. rdmsrl(msr, allowed);
  2245. return ctl_opt & allowed;
  2246. }
  2247. static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
  2248. struct vmx_capability *vmx_cap)
  2249. {
  2250. u32 vmx_msr_low, vmx_msr_high;
  2251. u32 _pin_based_exec_control = 0;
  2252. u32 _cpu_based_exec_control = 0;
  2253. u32 _cpu_based_2nd_exec_control = 0;
  2254. u64 _cpu_based_3rd_exec_control = 0;
  2255. u32 _vmexit_control = 0;
  2256. u32 _vmentry_control = 0;
  2257. u64 misc_msr;
  2258. int i;
  2259. /*
  2260. * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
  2261. * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
  2262. * intercepts writes to PAT and EFER, i.e. never enables those controls.
  2263. */
  2264. struct {
  2265. u32 entry_control;
  2266. u32 exit_control;
  2267. } const vmcs_entry_exit_pairs[] = {
  2268. { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
  2269. { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
  2270. { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
  2271. { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
  2272. { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
  2273. };
  2274. memset(vmcs_conf, 0, sizeof(*vmcs_conf));
  2275. if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
  2276. KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
  2277. MSR_IA32_VMX_PROCBASED_CTLS,
  2278. &_cpu_based_exec_control))
  2279. return -EIO;
  2280. if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
  2281. if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
  2282. KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
  2283. MSR_IA32_VMX_PROCBASED_CTLS2,
  2284. &_cpu_based_2nd_exec_control))
  2285. return -EIO;
  2286. }
  2287. #ifndef CONFIG_X86_64
  2288. if (!(_cpu_based_2nd_exec_control &
  2289. SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
  2290. _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
  2291. #endif
  2292. if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
  2293. _cpu_based_2nd_exec_control &= ~(
  2294. SECONDARY_EXEC_APIC_REGISTER_VIRT |
  2295. SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
  2296. SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
  2297. rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
  2298. &vmx_cap->ept, &vmx_cap->vpid);
  2299. if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
  2300. vmx_cap->ept) {
  2301. pr_warn_once("EPT CAP should not exist if not support "
  2302. "1-setting enable EPT VM-execution control\n");
  2303. if (error_on_inconsistent_vmcs_config)
  2304. return -EIO;
  2305. vmx_cap->ept = 0;
  2306. }
  2307. if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
  2308. vmx_cap->vpid) {
  2309. pr_warn_once("VPID CAP should not exist if not support "
  2310. "1-setting enable VPID VM-execution control\n");
  2311. if (error_on_inconsistent_vmcs_config)
  2312. return -EIO;
  2313. vmx_cap->vpid = 0;
  2314. }
  2315. if (!cpu_has_sgx())
  2316. _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
  2317. if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
  2318. _cpu_based_3rd_exec_control =
  2319. adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
  2320. MSR_IA32_VMX_PROCBASED_CTLS3);
  2321. if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
  2322. KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
  2323. MSR_IA32_VMX_EXIT_CTLS,
  2324. &_vmexit_control))
  2325. return -EIO;
  2326. if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
  2327. KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
  2328. MSR_IA32_VMX_PINBASED_CTLS,
  2329. &_pin_based_exec_control))
  2330. return -EIO;
  2331. if (cpu_has_broken_vmx_preemption_timer())
  2332. _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
  2333. if (!(_cpu_based_2nd_exec_control &
  2334. SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
  2335. _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
  2336. if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
  2337. KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
  2338. MSR_IA32_VMX_ENTRY_CTLS,
  2339. &_vmentry_control))
  2340. return -EIO;
  2341. for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
  2342. u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
  2343. u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
  2344. if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
  2345. continue;
  2346. pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
  2347. _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
  2348. if (error_on_inconsistent_vmcs_config)
  2349. return -EIO;
  2350. _vmentry_control &= ~n_ctrl;
  2351. _vmexit_control &= ~x_ctrl;
  2352. }
  2353. rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
  2354. /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
  2355. if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
  2356. return -EIO;
  2357. #ifdef CONFIG_X86_64
  2358. /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
  2359. if (vmx_msr_high & (1u<<16))
  2360. return -EIO;
  2361. #endif
  2362. /* Require Write-Back (WB) memory type for VMCS accesses. */
  2363. if (((vmx_msr_high >> 18) & 15) != 6)
  2364. return -EIO;
  2365. rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
  2366. vmcs_conf->size = vmx_msr_high & 0x1fff;
  2367. vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
  2368. vmcs_conf->revision_id = vmx_msr_low;
  2369. vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
  2370. vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
  2371. vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
  2372. vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
  2373. vmcs_conf->vmexit_ctrl = _vmexit_control;
  2374. vmcs_conf->vmentry_ctrl = _vmentry_control;
  2375. vmcs_conf->misc = misc_msr;
  2376. return 0;
  2377. }
  2378. struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
  2379. {
  2380. int node = cpu_to_node(cpu);
  2381. struct page *pages;
  2382. struct vmcs *vmcs;
  2383. pages = __alloc_pages_node(node, flags, 0);
  2384. if (!pages)
  2385. return NULL;
  2386. vmcs = page_address(pages);
  2387. memset(vmcs, 0, vmcs_config.size);
  2388. /* KVM supports Enlightened VMCS v1 only */
  2389. if (static_branch_unlikely(&enable_evmcs))
  2390. vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
  2391. else
  2392. vmcs->hdr.revision_id = vmcs_config.revision_id;
  2393. if (shadow)
  2394. vmcs->hdr.shadow_vmcs = 1;
  2395. return vmcs;
  2396. }
  2397. void free_vmcs(struct vmcs *vmcs)
  2398. {
  2399. free_page((unsigned long)vmcs);
  2400. }
  2401. /*
  2402. * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
  2403. */
  2404. void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
  2405. {
  2406. if (!loaded_vmcs->vmcs)
  2407. return;
  2408. loaded_vmcs_clear(loaded_vmcs);
  2409. free_vmcs(loaded_vmcs->vmcs);
  2410. loaded_vmcs->vmcs = NULL;
  2411. if (loaded_vmcs->msr_bitmap)
  2412. free_page((unsigned long)loaded_vmcs->msr_bitmap);
  2413. WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
  2414. }
  2415. int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
  2416. {
  2417. loaded_vmcs->vmcs = alloc_vmcs(false);
  2418. if (!loaded_vmcs->vmcs)
  2419. return -ENOMEM;
  2420. vmcs_clear(loaded_vmcs->vmcs);
  2421. loaded_vmcs->shadow_vmcs = NULL;
  2422. loaded_vmcs->hv_timer_soft_disabled = false;
  2423. loaded_vmcs->cpu = -1;
  2424. loaded_vmcs->launched = 0;
  2425. if (cpu_has_vmx_msr_bitmap()) {
  2426. loaded_vmcs->msr_bitmap = (unsigned long *)
  2427. __get_free_page(GFP_KERNEL_ACCOUNT);
  2428. if (!loaded_vmcs->msr_bitmap)
  2429. goto out_vmcs;
  2430. memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
  2431. }
  2432. memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
  2433. memset(&loaded_vmcs->controls_shadow, 0,
  2434. sizeof(struct vmcs_controls_shadow));
  2435. return 0;
  2436. out_vmcs:
  2437. free_loaded_vmcs(loaded_vmcs);
  2438. return -ENOMEM;
  2439. }
  2440. static void free_kvm_area(void)
  2441. {
  2442. int cpu;
  2443. for_each_possible_cpu(cpu) {
  2444. free_vmcs(per_cpu(vmxarea, cpu));
  2445. per_cpu(vmxarea, cpu) = NULL;
  2446. }
  2447. }
  2448. static __init int alloc_kvm_area(void)
  2449. {
  2450. int cpu;
  2451. for_each_possible_cpu(cpu) {
  2452. struct vmcs *vmcs;
  2453. vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
  2454. if (!vmcs) {
  2455. free_kvm_area();
  2456. return -ENOMEM;
  2457. }
  2458. /*
  2459. * When eVMCS is enabled, alloc_vmcs_cpu() sets
  2460. * vmcs->revision_id to KVM_EVMCS_VERSION instead of
  2461. * revision_id reported by MSR_IA32_VMX_BASIC.
  2462. *
  2463. * However, even though not explicitly documented by
  2464. * TLFS, VMXArea passed as VMXON argument should
  2465. * still be marked with revision_id reported by
  2466. * physical CPU.
  2467. */
  2468. if (static_branch_unlikely(&enable_evmcs))
  2469. vmcs->hdr.revision_id = vmcs_config.revision_id;
  2470. per_cpu(vmxarea, cpu) = vmcs;
  2471. }
  2472. return 0;
  2473. }
  2474. static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
  2475. struct kvm_segment *save)
  2476. {
  2477. if (!emulate_invalid_guest_state) {
  2478. /*
  2479. * CS and SS RPL should be equal during guest entry according
  2480. * to VMX spec, but in reality it is not always so. Since vcpu
  2481. * is in the middle of the transition from real mode to
  2482. * protected mode it is safe to assume that RPL 0 is a good
  2483. * default value.
  2484. */
  2485. if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
  2486. save->selector &= ~SEGMENT_RPL_MASK;
  2487. save->dpl = save->selector & SEGMENT_RPL_MASK;
  2488. save->s = 1;
  2489. }
  2490. __vmx_set_segment(vcpu, save, seg);
  2491. }
  2492. static void enter_pmode(struct kvm_vcpu *vcpu)
  2493. {
  2494. unsigned long flags;
  2495. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2496. /*
  2497. * Update real mode segment cache. It may be not up-to-date if segment
  2498. * register was written while vcpu was in a guest mode.
  2499. */
  2500. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
  2501. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
  2502. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
  2503. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
  2504. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
  2505. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
  2506. vmx->rmode.vm86_active = 0;
  2507. __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
  2508. flags = vmcs_readl(GUEST_RFLAGS);
  2509. flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
  2510. flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
  2511. vmcs_writel(GUEST_RFLAGS, flags);
  2512. vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
  2513. (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
  2514. vmx_update_exception_bitmap(vcpu);
  2515. fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
  2516. fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
  2517. fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
  2518. fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
  2519. fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
  2520. fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
  2521. }
  2522. static void fix_rmode_seg(int seg, struct kvm_segment *save)
  2523. {
  2524. const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
  2525. struct kvm_segment var = *save;
  2526. var.dpl = 0x3;
  2527. if (seg == VCPU_SREG_CS)
  2528. var.type = 0x3;
  2529. if (!emulate_invalid_guest_state) {
  2530. var.selector = var.base >> 4;
  2531. var.base = var.base & 0xffff0;
  2532. var.limit = 0xffff;
  2533. var.g = 0;
  2534. var.db = 0;
  2535. var.present = 1;
  2536. var.s = 1;
  2537. var.l = 0;
  2538. var.unusable = 0;
  2539. var.type = 0x3;
  2540. var.avl = 0;
  2541. if (save->base & 0xf)
  2542. printk_once(KERN_WARNING "kvm: segment base is not "
  2543. "paragraph aligned when entering "
  2544. "protected mode (seg=%d)", seg);
  2545. }
  2546. vmcs_write16(sf->selector, var.selector);
  2547. vmcs_writel(sf->base, var.base);
  2548. vmcs_write32(sf->limit, var.limit);
  2549. vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
  2550. }
  2551. static void enter_rmode(struct kvm_vcpu *vcpu)
  2552. {
  2553. unsigned long flags;
  2554. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2555. struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
  2556. /*
  2557. * KVM should never use VM86 to virtualize Real Mode when L2 is active,
  2558. * as using VM86 is unnecessary if unrestricted guest is enabled, and
  2559. * if unrestricted guest is disabled, VM-Enter (from L1) with CR0.PG=0
  2560. * should VM-Fail and KVM should reject userspace attempts to stuff
  2561. * CR0.PG=0 when L2 is active.
  2562. */
  2563. WARN_ON_ONCE(is_guest_mode(vcpu));
  2564. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
  2565. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
  2566. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
  2567. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
  2568. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
  2569. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
  2570. vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
  2571. vmx->rmode.vm86_active = 1;
  2572. /*
  2573. * Very old userspace does not call KVM_SET_TSS_ADDR before entering
  2574. * vcpu. Warn the user that an update is overdue.
  2575. */
  2576. if (!kvm_vmx->tss_addr)
  2577. printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
  2578. "called before entering vcpu\n");
  2579. vmx_segment_cache_clear(vmx);
  2580. vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
  2581. vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
  2582. vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
  2583. flags = vmcs_readl(GUEST_RFLAGS);
  2584. vmx->rmode.save_rflags = flags;
  2585. flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
  2586. vmcs_writel(GUEST_RFLAGS, flags);
  2587. vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
  2588. vmx_update_exception_bitmap(vcpu);
  2589. fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
  2590. fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
  2591. fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
  2592. fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
  2593. fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
  2594. fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
  2595. }
  2596. int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
  2597. {
  2598. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2599. /* Nothing to do if hardware doesn't support EFER. */
  2600. if (!vmx_find_uret_msr(vmx, MSR_EFER))
  2601. return 0;
  2602. vcpu->arch.efer = efer;
  2603. #ifdef CONFIG_X86_64
  2604. if (efer & EFER_LMA)
  2605. vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
  2606. else
  2607. vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
  2608. #else
  2609. if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
  2610. return 1;
  2611. #endif
  2612. vmx_setup_uret_msrs(vmx);
  2613. return 0;
  2614. }
  2615. #ifdef CONFIG_X86_64
  2616. static void enter_lmode(struct kvm_vcpu *vcpu)
  2617. {
  2618. u32 guest_tr_ar;
  2619. vmx_segment_cache_clear(to_vmx(vcpu));
  2620. guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
  2621. if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
  2622. pr_debug_ratelimited("%s: tss fixup for long mode. \n",
  2623. __func__);
  2624. vmcs_write32(GUEST_TR_AR_BYTES,
  2625. (guest_tr_ar & ~VMX_AR_TYPE_MASK)
  2626. | VMX_AR_TYPE_BUSY_64_TSS);
  2627. }
  2628. vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
  2629. }
  2630. static void exit_lmode(struct kvm_vcpu *vcpu)
  2631. {
  2632. vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
  2633. }
  2634. #endif
  2635. static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
  2636. {
  2637. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2638. /*
  2639. * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
  2640. * the CPU is not required to invalidate guest-physical mappings on
  2641. * VM-Entry, even if VPID is disabled. Guest-physical mappings are
  2642. * associated with the root EPT structure and not any particular VPID
  2643. * (INVVPID also isn't required to invalidate guest-physical mappings).
  2644. */
  2645. if (enable_ept) {
  2646. ept_sync_global();
  2647. } else if (enable_vpid) {
  2648. if (cpu_has_vmx_invvpid_global()) {
  2649. vpid_sync_vcpu_global();
  2650. } else {
  2651. vpid_sync_vcpu_single(vmx->vpid);
  2652. vpid_sync_vcpu_single(vmx->nested.vpid02);
  2653. }
  2654. }
  2655. }
  2656. static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
  2657. {
  2658. if (is_guest_mode(vcpu))
  2659. return nested_get_vpid02(vcpu);
  2660. return to_vmx(vcpu)->vpid;
  2661. }
  2662. static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
  2663. {
  2664. struct kvm_mmu *mmu = vcpu->arch.mmu;
  2665. u64 root_hpa = mmu->root.hpa;
  2666. /* No flush required if the current context is invalid. */
  2667. if (!VALID_PAGE(root_hpa))
  2668. return;
  2669. if (enable_ept)
  2670. ept_sync_context(construct_eptp(vcpu, root_hpa,
  2671. mmu->root_role.level));
  2672. else
  2673. vpid_sync_context(vmx_get_current_vpid(vcpu));
  2674. }
  2675. static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
  2676. {
  2677. /*
  2678. * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
  2679. * vmx_flush_tlb_guest() for an explanation of why this is ok.
  2680. */
  2681. vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
  2682. }
  2683. static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
  2684. {
  2685. /*
  2686. * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
  2687. * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
  2688. * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
  2689. * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
  2690. * i.e. no explicit INVVPID is necessary.
  2691. */
  2692. vpid_sync_context(vmx_get_current_vpid(vcpu));
  2693. }
  2694. void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
  2695. {
  2696. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  2697. if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
  2698. return;
  2699. if (is_pae_paging(vcpu)) {
  2700. vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
  2701. vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
  2702. vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
  2703. vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
  2704. }
  2705. }
  2706. void ept_save_pdptrs(struct kvm_vcpu *vcpu)
  2707. {
  2708. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  2709. if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
  2710. return;
  2711. mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
  2712. mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
  2713. mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
  2714. mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
  2715. kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
  2716. }
  2717. #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
  2718. CPU_BASED_CR3_STORE_EXITING)
  2719. static bool vmx_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  2720. {
  2721. if (is_guest_mode(vcpu))
  2722. return nested_guest_cr0_valid(vcpu, cr0);
  2723. if (to_vmx(vcpu)->nested.vmxon)
  2724. return nested_host_cr0_valid(vcpu, cr0);
  2725. return true;
  2726. }
  2727. void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  2728. {
  2729. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2730. unsigned long hw_cr0, old_cr0_pg;
  2731. u32 tmp;
  2732. old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
  2733. hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
  2734. if (enable_unrestricted_guest)
  2735. hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
  2736. else {
  2737. hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
  2738. if (!enable_ept)
  2739. hw_cr0 |= X86_CR0_WP;
  2740. if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
  2741. enter_pmode(vcpu);
  2742. if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
  2743. enter_rmode(vcpu);
  2744. }
  2745. vmcs_writel(CR0_READ_SHADOW, cr0);
  2746. vmcs_writel(GUEST_CR0, hw_cr0);
  2747. vcpu->arch.cr0 = cr0;
  2748. kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
  2749. #ifdef CONFIG_X86_64
  2750. if (vcpu->arch.efer & EFER_LME) {
  2751. if (!old_cr0_pg && (cr0 & X86_CR0_PG))
  2752. enter_lmode(vcpu);
  2753. else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
  2754. exit_lmode(vcpu);
  2755. }
  2756. #endif
  2757. if (enable_ept && !enable_unrestricted_guest) {
  2758. /*
  2759. * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
  2760. * the below code _enables_ CR3 exiting, vmx_cache_reg() will
  2761. * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
  2762. * KVM's CR3 is installed.
  2763. */
  2764. if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
  2765. vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
  2766. /*
  2767. * When running with EPT but not unrestricted guest, KVM must
  2768. * intercept CR3 accesses when paging is _disabled_. This is
  2769. * necessary because restricted guests can't actually run with
  2770. * paging disabled, and so KVM stuffs its own CR3 in order to
  2771. * run the guest when identity mapped page tables.
  2772. *
  2773. * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
  2774. * update, it may be stale with respect to CR3 interception,
  2775. * e.g. after nested VM-Enter.
  2776. *
  2777. * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
  2778. * stores to forward them to L1, even if KVM does not need to
  2779. * intercept them to preserve its identity mapped page tables.
  2780. */
  2781. if (!(cr0 & X86_CR0_PG)) {
  2782. exec_controls_setbit(vmx, CR3_EXITING_BITS);
  2783. } else if (!is_guest_mode(vcpu)) {
  2784. exec_controls_clearbit(vmx, CR3_EXITING_BITS);
  2785. } else {
  2786. tmp = exec_controls_get(vmx);
  2787. tmp &= ~CR3_EXITING_BITS;
  2788. tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
  2789. exec_controls_set(vmx, tmp);
  2790. }
  2791. /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
  2792. if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
  2793. vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
  2794. /*
  2795. * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
  2796. * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
  2797. */
  2798. if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
  2799. kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
  2800. }
  2801. /* depends on vcpu->arch.cr0 to be set to a new value */
  2802. vmx->emulation_required = vmx_emulation_required(vcpu);
  2803. }
  2804. static int vmx_get_max_tdp_level(void)
  2805. {
  2806. if (cpu_has_vmx_ept_5levels())
  2807. return 5;
  2808. return 4;
  2809. }
  2810. u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
  2811. {
  2812. u64 eptp = VMX_EPTP_MT_WB;
  2813. eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
  2814. if (enable_ept_ad_bits &&
  2815. (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
  2816. eptp |= VMX_EPTP_AD_ENABLE_BIT;
  2817. eptp |= root_hpa;
  2818. return eptp;
  2819. }
  2820. static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
  2821. int root_level)
  2822. {
  2823. struct kvm *kvm = vcpu->kvm;
  2824. bool update_guest_cr3 = true;
  2825. unsigned long guest_cr3;
  2826. u64 eptp;
  2827. if (enable_ept) {
  2828. eptp = construct_eptp(vcpu, root_hpa, root_level);
  2829. vmcs_write64(EPT_POINTER, eptp);
  2830. hv_track_root_tdp(vcpu, root_hpa);
  2831. if (!enable_unrestricted_guest && !is_paging(vcpu))
  2832. guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
  2833. else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
  2834. guest_cr3 = vcpu->arch.cr3;
  2835. else /* vmcs.GUEST_CR3 is already up-to-date. */
  2836. update_guest_cr3 = false;
  2837. vmx_ept_load_pdptrs(vcpu);
  2838. } else {
  2839. guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
  2840. }
  2841. if (update_guest_cr3)
  2842. vmcs_writel(GUEST_CR3, guest_cr3);
  2843. }
  2844. static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  2845. {
  2846. /*
  2847. * We operate under the default treatment of SMM, so VMX cannot be
  2848. * enabled under SMM. Note, whether or not VMXE is allowed at all,
  2849. * i.e. is a reserved bit, is handled by common x86 code.
  2850. */
  2851. if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
  2852. return false;
  2853. if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
  2854. return false;
  2855. return true;
  2856. }
  2857. void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  2858. {
  2859. unsigned long old_cr4 = vcpu->arch.cr4;
  2860. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2861. /*
  2862. * Pass through host's Machine Check Enable value to hw_cr4, which
  2863. * is in force while we are in guest mode. Do not let guests control
  2864. * this bit, even if host CR4.MCE == 0.
  2865. */
  2866. unsigned long hw_cr4;
  2867. hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
  2868. if (enable_unrestricted_guest)
  2869. hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
  2870. else if (vmx->rmode.vm86_active)
  2871. hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
  2872. else
  2873. hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
  2874. if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
  2875. if (cr4 & X86_CR4_UMIP) {
  2876. secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
  2877. hw_cr4 &= ~X86_CR4_UMIP;
  2878. } else if (!is_guest_mode(vcpu) ||
  2879. !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
  2880. secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
  2881. }
  2882. }
  2883. vcpu->arch.cr4 = cr4;
  2884. kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
  2885. if (!enable_unrestricted_guest) {
  2886. if (enable_ept) {
  2887. if (!is_paging(vcpu)) {
  2888. hw_cr4 &= ~X86_CR4_PAE;
  2889. hw_cr4 |= X86_CR4_PSE;
  2890. } else if (!(cr4 & X86_CR4_PAE)) {
  2891. hw_cr4 &= ~X86_CR4_PAE;
  2892. }
  2893. }
  2894. /*
  2895. * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
  2896. * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
  2897. * to be manually disabled when guest switches to non-paging
  2898. * mode.
  2899. *
  2900. * If !enable_unrestricted_guest, the CPU is always running
  2901. * with CR0.PG=1 and CR4 needs to be modified.
  2902. * If enable_unrestricted_guest, the CPU automatically
  2903. * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
  2904. */
  2905. if (!is_paging(vcpu))
  2906. hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
  2907. }
  2908. vmcs_writel(CR4_READ_SHADOW, cr4);
  2909. vmcs_writel(GUEST_CR4, hw_cr4);
  2910. if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  2911. kvm_update_cpuid_runtime(vcpu);
  2912. }
  2913. void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  2914. {
  2915. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2916. u32 ar;
  2917. if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
  2918. *var = vmx->rmode.segs[seg];
  2919. if (seg == VCPU_SREG_TR
  2920. || var->selector == vmx_read_guest_seg_selector(vmx, seg))
  2921. return;
  2922. var->base = vmx_read_guest_seg_base(vmx, seg);
  2923. var->selector = vmx_read_guest_seg_selector(vmx, seg);
  2924. return;
  2925. }
  2926. var->base = vmx_read_guest_seg_base(vmx, seg);
  2927. var->limit = vmx_read_guest_seg_limit(vmx, seg);
  2928. var->selector = vmx_read_guest_seg_selector(vmx, seg);
  2929. ar = vmx_read_guest_seg_ar(vmx, seg);
  2930. var->unusable = (ar >> 16) & 1;
  2931. var->type = ar & 15;
  2932. var->s = (ar >> 4) & 1;
  2933. var->dpl = (ar >> 5) & 3;
  2934. /*
  2935. * Some userspaces do not preserve unusable property. Since usable
  2936. * segment has to be present according to VMX spec we can use present
  2937. * property to amend userspace bug by making unusable segment always
  2938. * nonpresent. vmx_segment_access_rights() already marks nonpresent
  2939. * segment as unusable.
  2940. */
  2941. var->present = !var->unusable;
  2942. var->avl = (ar >> 12) & 1;
  2943. var->l = (ar >> 13) & 1;
  2944. var->db = (ar >> 14) & 1;
  2945. var->g = (ar >> 15) & 1;
  2946. }
  2947. static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
  2948. {
  2949. struct kvm_segment s;
  2950. if (to_vmx(vcpu)->rmode.vm86_active) {
  2951. vmx_get_segment(vcpu, &s, seg);
  2952. return s.base;
  2953. }
  2954. return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
  2955. }
  2956. int vmx_get_cpl(struct kvm_vcpu *vcpu)
  2957. {
  2958. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2959. if (unlikely(vmx->rmode.vm86_active))
  2960. return 0;
  2961. else {
  2962. int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
  2963. return VMX_AR_DPL(ar);
  2964. }
  2965. }
  2966. static u32 vmx_segment_access_rights(struct kvm_segment *var)
  2967. {
  2968. u32 ar;
  2969. ar = var->type & 15;
  2970. ar |= (var->s & 1) << 4;
  2971. ar |= (var->dpl & 3) << 5;
  2972. ar |= (var->present & 1) << 7;
  2973. ar |= (var->avl & 1) << 12;
  2974. ar |= (var->l & 1) << 13;
  2975. ar |= (var->db & 1) << 14;
  2976. ar |= (var->g & 1) << 15;
  2977. ar |= (var->unusable || !var->present) << 16;
  2978. return ar;
  2979. }
  2980. void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  2981. {
  2982. struct vcpu_vmx *vmx = to_vmx(vcpu);
  2983. const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
  2984. vmx_segment_cache_clear(vmx);
  2985. if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
  2986. vmx->rmode.segs[seg] = *var;
  2987. if (seg == VCPU_SREG_TR)
  2988. vmcs_write16(sf->selector, var->selector);
  2989. else if (var->s)
  2990. fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
  2991. return;
  2992. }
  2993. vmcs_writel(sf->base, var->base);
  2994. vmcs_write32(sf->limit, var->limit);
  2995. vmcs_write16(sf->selector, var->selector);
  2996. /*
  2997. * Fix the "Accessed" bit in AR field of segment registers for older
  2998. * qemu binaries.
  2999. * IA32 arch specifies that at the time of processor reset the
  3000. * "Accessed" bit in the AR field of segment registers is 1. And qemu
  3001. * is setting it to 0 in the userland code. This causes invalid guest
  3002. * state vmexit when "unrestricted guest" mode is turned on.
  3003. * Fix for this setup issue in cpu_reset is being pushed in the qemu
  3004. * tree. Newer qemu binaries with that qemu fix would not need this
  3005. * kvm hack.
  3006. */
  3007. if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
  3008. var->type |= 0x1; /* Accessed */
  3009. vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
  3010. }
  3011. static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
  3012. {
  3013. __vmx_set_segment(vcpu, var, seg);
  3014. to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
  3015. }
  3016. static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  3017. {
  3018. u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
  3019. *db = (ar >> 14) & 1;
  3020. *l = (ar >> 13) & 1;
  3021. }
  3022. static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  3023. {
  3024. dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
  3025. dt->address = vmcs_readl(GUEST_IDTR_BASE);
  3026. }
  3027. static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  3028. {
  3029. vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
  3030. vmcs_writel(GUEST_IDTR_BASE, dt->address);
  3031. }
  3032. static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  3033. {
  3034. dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
  3035. dt->address = vmcs_readl(GUEST_GDTR_BASE);
  3036. }
  3037. static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
  3038. {
  3039. vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
  3040. vmcs_writel(GUEST_GDTR_BASE, dt->address);
  3041. }
  3042. static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
  3043. {
  3044. struct kvm_segment var;
  3045. u32 ar;
  3046. vmx_get_segment(vcpu, &var, seg);
  3047. var.dpl = 0x3;
  3048. if (seg == VCPU_SREG_CS)
  3049. var.type = 0x3;
  3050. ar = vmx_segment_access_rights(&var);
  3051. if (var.base != (var.selector << 4))
  3052. return false;
  3053. if (var.limit != 0xffff)
  3054. return false;
  3055. if (ar != 0xf3)
  3056. return false;
  3057. return true;
  3058. }
  3059. static bool code_segment_valid(struct kvm_vcpu *vcpu)
  3060. {
  3061. struct kvm_segment cs;
  3062. unsigned int cs_rpl;
  3063. vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
  3064. cs_rpl = cs.selector & SEGMENT_RPL_MASK;
  3065. if (cs.unusable)
  3066. return false;
  3067. if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
  3068. return false;
  3069. if (!cs.s)
  3070. return false;
  3071. if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
  3072. if (cs.dpl > cs_rpl)
  3073. return false;
  3074. } else {
  3075. if (cs.dpl != cs_rpl)
  3076. return false;
  3077. }
  3078. if (!cs.present)
  3079. return false;
  3080. /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
  3081. return true;
  3082. }
  3083. static bool stack_segment_valid(struct kvm_vcpu *vcpu)
  3084. {
  3085. struct kvm_segment ss;
  3086. unsigned int ss_rpl;
  3087. vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
  3088. ss_rpl = ss.selector & SEGMENT_RPL_MASK;
  3089. if (ss.unusable)
  3090. return true;
  3091. if (ss.type != 3 && ss.type != 7)
  3092. return false;
  3093. if (!ss.s)
  3094. return false;
  3095. if (ss.dpl != ss_rpl) /* DPL != RPL */
  3096. return false;
  3097. if (!ss.present)
  3098. return false;
  3099. return true;
  3100. }
  3101. static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
  3102. {
  3103. struct kvm_segment var;
  3104. unsigned int rpl;
  3105. vmx_get_segment(vcpu, &var, seg);
  3106. rpl = var.selector & SEGMENT_RPL_MASK;
  3107. if (var.unusable)
  3108. return true;
  3109. if (!var.s)
  3110. return false;
  3111. if (!var.present)
  3112. return false;
  3113. if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
  3114. if (var.dpl < rpl) /* DPL < RPL */
  3115. return false;
  3116. }
  3117. /* TODO: Add other members to kvm_segment_field to allow checking for other access
  3118. * rights flags
  3119. */
  3120. return true;
  3121. }
  3122. static bool tr_valid(struct kvm_vcpu *vcpu)
  3123. {
  3124. struct kvm_segment tr;
  3125. vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
  3126. if (tr.unusable)
  3127. return false;
  3128. if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
  3129. return false;
  3130. if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
  3131. return false;
  3132. if (!tr.present)
  3133. return false;
  3134. return true;
  3135. }
  3136. static bool ldtr_valid(struct kvm_vcpu *vcpu)
  3137. {
  3138. struct kvm_segment ldtr;
  3139. vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
  3140. if (ldtr.unusable)
  3141. return true;
  3142. if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
  3143. return false;
  3144. if (ldtr.type != 2)
  3145. return false;
  3146. if (!ldtr.present)
  3147. return false;
  3148. return true;
  3149. }
  3150. static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
  3151. {
  3152. struct kvm_segment cs, ss;
  3153. vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
  3154. vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
  3155. return ((cs.selector & SEGMENT_RPL_MASK) ==
  3156. (ss.selector & SEGMENT_RPL_MASK));
  3157. }
  3158. /*
  3159. * Check if guest state is valid. Returns true if valid, false if
  3160. * not.
  3161. * We assume that registers are always usable
  3162. */
  3163. bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
  3164. {
  3165. /* real mode guest state checks */
  3166. if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
  3167. if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
  3168. return false;
  3169. if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
  3170. return false;
  3171. if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
  3172. return false;
  3173. if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
  3174. return false;
  3175. if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
  3176. return false;
  3177. if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
  3178. return false;
  3179. } else {
  3180. /* protected mode guest state checks */
  3181. if (!cs_ss_rpl_check(vcpu))
  3182. return false;
  3183. if (!code_segment_valid(vcpu))
  3184. return false;
  3185. if (!stack_segment_valid(vcpu))
  3186. return false;
  3187. if (!data_segment_valid(vcpu, VCPU_SREG_DS))
  3188. return false;
  3189. if (!data_segment_valid(vcpu, VCPU_SREG_ES))
  3190. return false;
  3191. if (!data_segment_valid(vcpu, VCPU_SREG_FS))
  3192. return false;
  3193. if (!data_segment_valid(vcpu, VCPU_SREG_GS))
  3194. return false;
  3195. if (!tr_valid(vcpu))
  3196. return false;
  3197. if (!ldtr_valid(vcpu))
  3198. return false;
  3199. }
  3200. /* TODO:
  3201. * - Add checks on RIP
  3202. * - Add checks on RFLAGS
  3203. */
  3204. return true;
  3205. }
  3206. static int init_rmode_tss(struct kvm *kvm, void __user *ua)
  3207. {
  3208. const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
  3209. u16 data;
  3210. int i;
  3211. for (i = 0; i < 3; i++) {
  3212. if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
  3213. return -EFAULT;
  3214. }
  3215. data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
  3216. if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
  3217. return -EFAULT;
  3218. data = ~0;
  3219. if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
  3220. return -EFAULT;
  3221. return 0;
  3222. }
  3223. static int init_rmode_identity_map(struct kvm *kvm)
  3224. {
  3225. struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
  3226. int i, r = 0;
  3227. void __user *uaddr;
  3228. u32 tmp;
  3229. /* Protect kvm_vmx->ept_identity_pagetable_done. */
  3230. mutex_lock(&kvm->slots_lock);
  3231. if (likely(kvm_vmx->ept_identity_pagetable_done))
  3232. goto out;
  3233. if (!kvm_vmx->ept_identity_map_addr)
  3234. kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
  3235. uaddr = __x86_set_memory_region(kvm,
  3236. IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
  3237. kvm_vmx->ept_identity_map_addr,
  3238. PAGE_SIZE);
  3239. if (IS_ERR(uaddr)) {
  3240. r = PTR_ERR(uaddr);
  3241. goto out;
  3242. }
  3243. /* Set up identity-mapping pagetable for EPT in real mode */
  3244. for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
  3245. tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
  3246. _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
  3247. if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
  3248. r = -EFAULT;
  3249. goto out;
  3250. }
  3251. }
  3252. kvm_vmx->ept_identity_pagetable_done = true;
  3253. out:
  3254. mutex_unlock(&kvm->slots_lock);
  3255. return r;
  3256. }
  3257. static void seg_setup(int seg)
  3258. {
  3259. const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
  3260. unsigned int ar;
  3261. vmcs_write16(sf->selector, 0);
  3262. vmcs_writel(sf->base, 0);
  3263. vmcs_write32(sf->limit, 0xffff);
  3264. ar = 0x93;
  3265. if (seg == VCPU_SREG_CS)
  3266. ar |= 0x08; /* code segment */
  3267. vmcs_write32(sf->ar_bytes, ar);
  3268. }
  3269. static int alloc_apic_access_page(struct kvm *kvm)
  3270. {
  3271. struct page *page;
  3272. void __user *hva;
  3273. int ret = 0;
  3274. mutex_lock(&kvm->slots_lock);
  3275. if (kvm->arch.apic_access_memslot_enabled)
  3276. goto out;
  3277. hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
  3278. APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
  3279. if (IS_ERR(hva)) {
  3280. ret = PTR_ERR(hva);
  3281. goto out;
  3282. }
  3283. page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  3284. if (is_error_page(page)) {
  3285. ret = -EFAULT;
  3286. goto out;
  3287. }
  3288. /*
  3289. * Do not pin the page in memory, so that memory hot-unplug
  3290. * is able to migrate it.
  3291. */
  3292. put_page(page);
  3293. kvm->arch.apic_access_memslot_enabled = true;
  3294. out:
  3295. mutex_unlock(&kvm->slots_lock);
  3296. return ret;
  3297. }
  3298. int allocate_vpid(void)
  3299. {
  3300. int vpid;
  3301. if (!enable_vpid)
  3302. return 0;
  3303. spin_lock(&vmx_vpid_lock);
  3304. vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
  3305. if (vpid < VMX_NR_VPIDS)
  3306. __set_bit(vpid, vmx_vpid_bitmap);
  3307. else
  3308. vpid = 0;
  3309. spin_unlock(&vmx_vpid_lock);
  3310. return vpid;
  3311. }
  3312. void free_vpid(int vpid)
  3313. {
  3314. if (!enable_vpid || vpid == 0)
  3315. return;
  3316. spin_lock(&vmx_vpid_lock);
  3317. __clear_bit(vpid, vmx_vpid_bitmap);
  3318. spin_unlock(&vmx_vpid_lock);
  3319. }
  3320. static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
  3321. {
  3322. /*
  3323. * When KVM is a nested hypervisor on top of Hyper-V and uses
  3324. * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
  3325. * bitmap has changed.
  3326. */
  3327. if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs)) {
  3328. struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
  3329. if (evmcs->hv_enlightenments_control.msr_bitmap)
  3330. evmcs->hv_clean_fields &=
  3331. ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
  3332. }
  3333. vmx->nested.force_msr_bitmap_recalc = true;
  3334. }
  3335. void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
  3336. {
  3337. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3338. unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
  3339. if (!cpu_has_vmx_msr_bitmap())
  3340. return;
  3341. vmx_msr_bitmap_l01_changed(vmx);
  3342. /*
  3343. * Mark the desired intercept state in shadow bitmap, this is needed
  3344. * for resync when the MSR filters change.
  3345. */
  3346. if (is_valid_passthrough_msr(msr)) {
  3347. int idx = possible_passthrough_msr_slot(msr);
  3348. if (idx != -ENOENT) {
  3349. if (type & MSR_TYPE_R)
  3350. clear_bit(idx, vmx->shadow_msr_intercept.read);
  3351. if (type & MSR_TYPE_W)
  3352. clear_bit(idx, vmx->shadow_msr_intercept.write);
  3353. }
  3354. }
  3355. if ((type & MSR_TYPE_R) &&
  3356. !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
  3357. vmx_set_msr_bitmap_read(msr_bitmap, msr);
  3358. type &= ~MSR_TYPE_R;
  3359. }
  3360. if ((type & MSR_TYPE_W) &&
  3361. !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
  3362. vmx_set_msr_bitmap_write(msr_bitmap, msr);
  3363. type &= ~MSR_TYPE_W;
  3364. }
  3365. if (type & MSR_TYPE_R)
  3366. vmx_clear_msr_bitmap_read(msr_bitmap, msr);
  3367. if (type & MSR_TYPE_W)
  3368. vmx_clear_msr_bitmap_write(msr_bitmap, msr);
  3369. }
  3370. void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
  3371. {
  3372. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3373. unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
  3374. if (!cpu_has_vmx_msr_bitmap())
  3375. return;
  3376. vmx_msr_bitmap_l01_changed(vmx);
  3377. /*
  3378. * Mark the desired intercept state in shadow bitmap, this is needed
  3379. * for resync when the MSR filter changes.
  3380. */
  3381. if (is_valid_passthrough_msr(msr)) {
  3382. int idx = possible_passthrough_msr_slot(msr);
  3383. if (idx != -ENOENT) {
  3384. if (type & MSR_TYPE_R)
  3385. set_bit(idx, vmx->shadow_msr_intercept.read);
  3386. if (type & MSR_TYPE_W)
  3387. set_bit(idx, vmx->shadow_msr_intercept.write);
  3388. }
  3389. }
  3390. if (type & MSR_TYPE_R)
  3391. vmx_set_msr_bitmap_read(msr_bitmap, msr);
  3392. if (type & MSR_TYPE_W)
  3393. vmx_set_msr_bitmap_write(msr_bitmap, msr);
  3394. }
  3395. static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
  3396. {
  3397. unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
  3398. unsigned long read_intercept;
  3399. int msr;
  3400. read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
  3401. for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
  3402. unsigned int read_idx = msr / BITS_PER_LONG;
  3403. unsigned int write_idx = read_idx + (0x800 / sizeof(long));
  3404. msr_bitmap[read_idx] = read_intercept;
  3405. msr_bitmap[write_idx] = ~0ul;
  3406. }
  3407. }
  3408. static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
  3409. {
  3410. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3411. u8 mode;
  3412. if (!cpu_has_vmx_msr_bitmap())
  3413. return;
  3414. if (cpu_has_secondary_exec_ctrls() &&
  3415. (secondary_exec_controls_get(vmx) &
  3416. SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
  3417. mode = MSR_BITMAP_MODE_X2APIC;
  3418. if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
  3419. mode |= MSR_BITMAP_MODE_X2APIC_APICV;
  3420. } else {
  3421. mode = 0;
  3422. }
  3423. if (mode == vmx->x2apic_msr_bitmap_mode)
  3424. return;
  3425. vmx->x2apic_msr_bitmap_mode = mode;
  3426. vmx_reset_x2apic_msrs(vcpu, mode);
  3427. /*
  3428. * TPR reads and writes can be virtualized even if virtual interrupt
  3429. * delivery is not in use.
  3430. */
  3431. vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
  3432. !(mode & MSR_BITMAP_MODE_X2APIC));
  3433. if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
  3434. vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
  3435. vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
  3436. vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
  3437. if (enable_ipiv)
  3438. vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
  3439. }
  3440. }
  3441. void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
  3442. {
  3443. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3444. bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
  3445. u32 i;
  3446. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
  3447. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
  3448. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
  3449. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
  3450. for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
  3451. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
  3452. vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
  3453. }
  3454. }
  3455. static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
  3456. {
  3457. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3458. void *vapic_page;
  3459. u32 vppr;
  3460. int rvi;
  3461. if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
  3462. !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
  3463. WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
  3464. return false;
  3465. rvi = vmx_get_rvi();
  3466. vapic_page = vmx->nested.virtual_apic_map.hva;
  3467. vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
  3468. return ((rvi & 0xf0) > (vppr & 0xf0));
  3469. }
  3470. static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
  3471. {
  3472. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3473. u32 i;
  3474. /*
  3475. * Redo intercept permissions for MSRs that KVM is passing through to
  3476. * the guest. Disabling interception will check the new MSR filter and
  3477. * ensure that KVM enables interception if usersepace wants to filter
  3478. * the MSR. MSRs that KVM is already intercepting don't need to be
  3479. * refreshed since KVM is going to intercept them regardless of what
  3480. * userspace wants.
  3481. */
  3482. for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
  3483. u32 msr = vmx_possible_passthrough_msrs[i];
  3484. if (!test_bit(i, vmx->shadow_msr_intercept.read))
  3485. vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
  3486. if (!test_bit(i, vmx->shadow_msr_intercept.write))
  3487. vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
  3488. }
  3489. /* PT MSRs can be passed through iff PT is exposed to the guest. */
  3490. if (vmx_pt_mode_is_host_guest())
  3491. pt_update_intercept_for_msr(vcpu);
  3492. }
  3493. static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
  3494. int pi_vec)
  3495. {
  3496. #ifdef CONFIG_SMP
  3497. if (vcpu->mode == IN_GUEST_MODE) {
  3498. /*
  3499. * The vector of the virtual has already been set in the PIR.
  3500. * Send a notification event to deliver the virtual interrupt
  3501. * unless the vCPU is the currently running vCPU, i.e. the
  3502. * event is being sent from a fastpath VM-Exit handler, in
  3503. * which case the PIR will be synced to the vIRR before
  3504. * re-entering the guest.
  3505. *
  3506. * When the target is not the running vCPU, the following
  3507. * possibilities emerge:
  3508. *
  3509. * Case 1: vCPU stays in non-root mode. Sending a notification
  3510. * event posts the interrupt to the vCPU.
  3511. *
  3512. * Case 2: vCPU exits to root mode and is still runnable. The
  3513. * PIR will be synced to the vIRR before re-entering the guest.
  3514. * Sending a notification event is ok as the host IRQ handler
  3515. * will ignore the spurious event.
  3516. *
  3517. * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
  3518. * has already synced PIR to vIRR and never blocks the vCPU if
  3519. * the vIRR is not empty. Therefore, a blocked vCPU here does
  3520. * not wait for any requested interrupts in PIR, and sending a
  3521. * notification event also results in a benign, spurious event.
  3522. */
  3523. if (vcpu != kvm_get_running_vcpu())
  3524. apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
  3525. return;
  3526. }
  3527. #endif
  3528. /*
  3529. * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
  3530. * otherwise do nothing as KVM will grab the highest priority pending
  3531. * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
  3532. */
  3533. kvm_vcpu_wake_up(vcpu);
  3534. }
  3535. static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
  3536. int vector)
  3537. {
  3538. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3539. if (is_guest_mode(vcpu) &&
  3540. vector == vmx->nested.posted_intr_nv) {
  3541. /*
  3542. * If a posted intr is not recognized by hardware,
  3543. * we will accomplish it in the next vmentry.
  3544. */
  3545. vmx->nested.pi_pending = true;
  3546. kvm_make_request(KVM_REQ_EVENT, vcpu);
  3547. /*
  3548. * This pairs with the smp_mb_*() after setting vcpu->mode in
  3549. * vcpu_enter_guest() to guarantee the vCPU sees the event
  3550. * request if triggering a posted interrupt "fails" because
  3551. * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
  3552. * the smb_wmb() in kvm_make_request() only ensures everything
  3553. * done before making the request is visible when the request
  3554. * is visible, it doesn't ensure ordering between the store to
  3555. * vcpu->requests and the load from vcpu->mode.
  3556. */
  3557. smp_mb__after_atomic();
  3558. /* the PIR and ON have been set by L1. */
  3559. kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
  3560. return 0;
  3561. }
  3562. return -1;
  3563. }
  3564. /*
  3565. * Send interrupt to vcpu via posted interrupt way.
  3566. * 1. If target vcpu is running(non-root mode), send posted interrupt
  3567. * notification to vcpu and hardware will sync PIR to vIRR atomically.
  3568. * 2. If target vcpu isn't running(root mode), kick it to pick up the
  3569. * interrupt from PIR in next vmentry.
  3570. */
  3571. static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
  3572. {
  3573. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3574. int r;
  3575. r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
  3576. if (!r)
  3577. return 0;
  3578. /* Note, this is called iff the local APIC is in-kernel. */
  3579. if (!vcpu->arch.apic->apicv_active)
  3580. return -1;
  3581. if (pi_test_and_set_pir(vector, &vmx->pi_desc))
  3582. return 0;
  3583. /* If a previous notification has sent the IPI, nothing to do. */
  3584. if (pi_test_and_set_on(&vmx->pi_desc))
  3585. return 0;
  3586. /*
  3587. * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
  3588. * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
  3589. * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
  3590. * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
  3591. */
  3592. kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
  3593. return 0;
  3594. }
  3595. static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
  3596. int trig_mode, int vector)
  3597. {
  3598. struct kvm_vcpu *vcpu = apic->vcpu;
  3599. if (vmx_deliver_posted_interrupt(vcpu, vector)) {
  3600. kvm_lapic_set_irr(vector, apic);
  3601. kvm_make_request(KVM_REQ_EVENT, vcpu);
  3602. kvm_vcpu_kick(vcpu);
  3603. } else {
  3604. trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
  3605. trig_mode, vector);
  3606. }
  3607. }
  3608. /*
  3609. * Set up the vmcs's constant host-state fields, i.e., host-state fields that
  3610. * will not change in the lifetime of the guest.
  3611. * Note that host-state that does change is set elsewhere. E.g., host-state
  3612. * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
  3613. */
  3614. void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
  3615. {
  3616. u32 low32, high32;
  3617. unsigned long tmpl;
  3618. unsigned long cr0, cr3, cr4;
  3619. cr0 = read_cr0();
  3620. WARN_ON(cr0 & X86_CR0_TS);
  3621. vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
  3622. /*
  3623. * Save the most likely value for this task's CR3 in the VMCS.
  3624. * We can't use __get_current_cr3_fast() because we're not atomic.
  3625. */
  3626. cr3 = __read_cr3();
  3627. vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
  3628. vmx->loaded_vmcs->host_state.cr3 = cr3;
  3629. /* Save the most likely value for this task's CR4 in the VMCS. */
  3630. cr4 = cr4_read_shadow();
  3631. vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
  3632. vmx->loaded_vmcs->host_state.cr4 = cr4;
  3633. vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
  3634. #ifdef CONFIG_X86_64
  3635. /*
  3636. * Load null selectors, so we can avoid reloading them in
  3637. * vmx_prepare_switch_to_host(), in case userspace uses
  3638. * the null selectors too (the expected case).
  3639. */
  3640. vmcs_write16(HOST_DS_SELECTOR, 0);
  3641. vmcs_write16(HOST_ES_SELECTOR, 0);
  3642. #else
  3643. vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
  3644. vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
  3645. #endif
  3646. vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
  3647. vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
  3648. vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
  3649. vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
  3650. rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
  3651. vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
  3652. /*
  3653. * SYSENTER is used for 32-bit system calls on either 32-bit or
  3654. * 64-bit kernels. It is always zero If neither is allowed, otherwise
  3655. * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
  3656. * have already done so!).
  3657. */
  3658. if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
  3659. vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
  3660. rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
  3661. vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
  3662. if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
  3663. rdmsr(MSR_IA32_CR_PAT, low32, high32);
  3664. vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
  3665. }
  3666. if (cpu_has_load_ia32_efer())
  3667. vmcs_write64(HOST_IA32_EFER, host_efer);
  3668. }
  3669. void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
  3670. {
  3671. struct kvm_vcpu *vcpu = &vmx->vcpu;
  3672. vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
  3673. ~vcpu->arch.cr4_guest_rsvd_bits;
  3674. if (!enable_ept) {
  3675. vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
  3676. vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
  3677. }
  3678. if (is_guest_mode(&vmx->vcpu))
  3679. vcpu->arch.cr4_guest_owned_bits &=
  3680. ~get_vmcs12(vcpu)->cr4_guest_host_mask;
  3681. vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
  3682. }
  3683. static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
  3684. {
  3685. u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
  3686. if (!kvm_vcpu_apicv_active(&vmx->vcpu))
  3687. pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
  3688. if (!enable_vnmi)
  3689. pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
  3690. if (!enable_preemption_timer)
  3691. pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
  3692. return pin_based_exec_ctrl;
  3693. }
  3694. static u32 vmx_vmentry_ctrl(void)
  3695. {
  3696. u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
  3697. if (vmx_pt_mode_is_system())
  3698. vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
  3699. VM_ENTRY_LOAD_IA32_RTIT_CTL);
  3700. /*
  3701. * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
  3702. */
  3703. vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
  3704. VM_ENTRY_LOAD_IA32_EFER |
  3705. VM_ENTRY_IA32E_MODE);
  3706. if (cpu_has_perf_global_ctrl_bug())
  3707. vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
  3708. return vmentry_ctrl;
  3709. }
  3710. static u32 vmx_vmexit_ctrl(void)
  3711. {
  3712. u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
  3713. /*
  3714. * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
  3715. * nested virtualization and thus allowed to be set in vmcs12.
  3716. */
  3717. vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
  3718. VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
  3719. if (vmx_pt_mode_is_system())
  3720. vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
  3721. VM_EXIT_CLEAR_IA32_RTIT_CTL);
  3722. if (cpu_has_perf_global_ctrl_bug())
  3723. vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
  3724. /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
  3725. return vmexit_ctrl &
  3726. ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
  3727. }
  3728. static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
  3729. {
  3730. struct vcpu_vmx *vmx = to_vmx(vcpu);
  3731. if (is_guest_mode(vcpu)) {
  3732. vmx->nested.update_vmcs01_apicv_status = true;
  3733. return;
  3734. }
  3735. pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
  3736. if (kvm_vcpu_apicv_active(vcpu)) {
  3737. secondary_exec_controls_setbit(vmx,
  3738. SECONDARY_EXEC_APIC_REGISTER_VIRT |
  3739. SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
  3740. if (enable_ipiv)
  3741. tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
  3742. } else {
  3743. secondary_exec_controls_clearbit(vmx,
  3744. SECONDARY_EXEC_APIC_REGISTER_VIRT |
  3745. SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
  3746. if (enable_ipiv)
  3747. tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
  3748. }
  3749. vmx_update_msr_bitmap_x2apic(vcpu);
  3750. }
  3751. static u32 vmx_exec_control(struct vcpu_vmx *vmx)
  3752. {
  3753. u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
  3754. /*
  3755. * Not used by KVM, but fully supported for nesting, i.e. are allowed in
  3756. * vmcs12 and propagated to vmcs02 when set in vmcs12.
  3757. */
  3758. exec_control &= ~(CPU_BASED_RDTSC_EXITING |
  3759. CPU_BASED_USE_IO_BITMAPS |
  3760. CPU_BASED_MONITOR_TRAP_FLAG |
  3761. CPU_BASED_PAUSE_EXITING);
  3762. /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
  3763. exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
  3764. CPU_BASED_NMI_WINDOW_EXITING);
  3765. if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
  3766. exec_control &= ~CPU_BASED_MOV_DR_EXITING;
  3767. if (!cpu_need_tpr_shadow(&vmx->vcpu))
  3768. exec_control &= ~CPU_BASED_TPR_SHADOW;
  3769. #ifdef CONFIG_X86_64
  3770. if (exec_control & CPU_BASED_TPR_SHADOW)
  3771. exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
  3772. CPU_BASED_CR8_STORE_EXITING);
  3773. else
  3774. exec_control |= CPU_BASED_CR8_STORE_EXITING |
  3775. CPU_BASED_CR8_LOAD_EXITING;
  3776. #endif
  3777. /* No need to intercept CR3 access or INVPLG when using EPT. */
  3778. if (enable_ept)
  3779. exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
  3780. CPU_BASED_CR3_STORE_EXITING |
  3781. CPU_BASED_INVLPG_EXITING);
  3782. if (kvm_mwait_in_guest(vmx->vcpu.kvm))
  3783. exec_control &= ~(CPU_BASED_MWAIT_EXITING |
  3784. CPU_BASED_MONITOR_EXITING);
  3785. if (kvm_hlt_in_guest(vmx->vcpu.kvm))
  3786. exec_control &= ~CPU_BASED_HLT_EXITING;
  3787. return exec_control;
  3788. }
  3789. static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
  3790. {
  3791. u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
  3792. /*
  3793. * IPI virtualization relies on APICv. Disable IPI virtualization if
  3794. * APICv is inhibited.
  3795. */
  3796. if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
  3797. exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
  3798. return exec_control;
  3799. }
  3800. /*
  3801. * Adjust a single secondary execution control bit to intercept/allow an
  3802. * instruction in the guest. This is usually done based on whether or not a
  3803. * feature has been exposed to the guest in order to correctly emulate faults.
  3804. */
  3805. static inline void
  3806. vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
  3807. u32 control, bool enabled, bool exiting)
  3808. {
  3809. /*
  3810. * If the control is for an opt-in feature, clear the control if the
  3811. * feature is not exposed to the guest, i.e. not enabled. If the
  3812. * control is opt-out, i.e. an exiting control, clear the control if
  3813. * the feature _is_ exposed to the guest, i.e. exiting/interception is
  3814. * disabled for the associated instruction. Note, the caller is
  3815. * responsible presetting exec_control to set all supported bits.
  3816. */
  3817. if (enabled == exiting)
  3818. *exec_control &= ~control;
  3819. /*
  3820. * Update the nested MSR settings so that a nested VMM can/can't set
  3821. * controls for features that are/aren't exposed to the guest.
  3822. */
  3823. if (nested) {
  3824. if (enabled)
  3825. vmx->nested.msrs.secondary_ctls_high |= control;
  3826. else
  3827. vmx->nested.msrs.secondary_ctls_high &= ~control;
  3828. }
  3829. }
  3830. /*
  3831. * Wrapper macro for the common case of adjusting a secondary execution control
  3832. * based on a single guest CPUID bit, with a dedicated feature bit. This also
  3833. * verifies that the control is actually supported by KVM and hardware.
  3834. */
  3835. #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
  3836. ({ \
  3837. bool __enabled; \
  3838. \
  3839. if (cpu_has_vmx_##name()) { \
  3840. __enabled = guest_cpuid_has(&(vmx)->vcpu, \
  3841. X86_FEATURE_##feat_name); \
  3842. vmx_adjust_secondary_exec_control(vmx, exec_control, \
  3843. SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
  3844. } \
  3845. })
  3846. /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
  3847. #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
  3848. vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
  3849. #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
  3850. vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
  3851. static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
  3852. {
  3853. struct kvm_vcpu *vcpu = &vmx->vcpu;
  3854. u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
  3855. if (vmx_pt_mode_is_system())
  3856. exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
  3857. if (!cpu_need_virtualize_apic_accesses(vcpu))
  3858. exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
  3859. if (vmx->vpid == 0)
  3860. exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
  3861. if (!enable_ept) {
  3862. exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
  3863. enable_unrestricted_guest = 0;
  3864. }
  3865. if (!enable_unrestricted_guest)
  3866. exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
  3867. if (kvm_pause_in_guest(vmx->vcpu.kvm))
  3868. exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
  3869. if (!kvm_vcpu_apicv_active(vcpu))
  3870. exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
  3871. SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
  3872. exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
  3873. /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
  3874. * in vmx_set_cr4. */
  3875. exec_control &= ~SECONDARY_EXEC_DESC;
  3876. /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
  3877. (handle_vmptrld).
  3878. We can NOT enable shadow_vmcs here because we don't have yet
  3879. a current VMCS12
  3880. */
  3881. exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
  3882. /*
  3883. * PML is enabled/disabled when dirty logging of memsmlots changes, but
  3884. * it needs to be set here when dirty logging is already active, e.g.
  3885. * if this vCPU was created after dirty logging was enabled.
  3886. */
  3887. if (!vcpu->kvm->arch.cpu_dirty_logging_count)
  3888. exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
  3889. if (cpu_has_vmx_xsaves()) {
  3890. /* Exposing XSAVES only when XSAVE is exposed */
  3891. bool xsaves_enabled =
  3892. boot_cpu_has(X86_FEATURE_XSAVE) &&
  3893. guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
  3894. guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
  3895. vcpu->arch.xsaves_enabled = xsaves_enabled;
  3896. vmx_adjust_secondary_exec_control(vmx, &exec_control,
  3897. SECONDARY_EXEC_XSAVES,
  3898. xsaves_enabled, false);
  3899. }
  3900. /*
  3901. * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
  3902. * feature is exposed to the guest. This creates a virtualization hole
  3903. * if both are supported in hardware but only one is exposed to the
  3904. * guest, but letting the guest execute RDTSCP or RDPID when either one
  3905. * is advertised is preferable to emulating the advertised instruction
  3906. * in KVM on #UD, and obviously better than incorrectly injecting #UD.
  3907. */
  3908. if (cpu_has_vmx_rdtscp()) {
  3909. bool rdpid_or_rdtscp_enabled =
  3910. guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
  3911. guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
  3912. vmx_adjust_secondary_exec_control(vmx, &exec_control,
  3913. SECONDARY_EXEC_ENABLE_RDTSCP,
  3914. rdpid_or_rdtscp_enabled, false);
  3915. }
  3916. vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
  3917. vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
  3918. vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
  3919. vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
  3920. ENABLE_USR_WAIT_PAUSE, false);
  3921. if (!vcpu->kvm->arch.bus_lock_detection_enabled)
  3922. exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
  3923. if (!kvm_notify_vmexit_enabled(vcpu->kvm))
  3924. exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
  3925. return exec_control;
  3926. }
  3927. static inline int vmx_get_pid_table_order(struct kvm *kvm)
  3928. {
  3929. return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
  3930. }
  3931. static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
  3932. {
  3933. struct page *pages;
  3934. struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
  3935. if (!irqchip_in_kernel(kvm) || !enable_ipiv)
  3936. return 0;
  3937. if (kvm_vmx->pid_table)
  3938. return 0;
  3939. pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, vmx_get_pid_table_order(kvm));
  3940. if (!pages)
  3941. return -ENOMEM;
  3942. kvm_vmx->pid_table = (void *)page_address(pages);
  3943. return 0;
  3944. }
  3945. static int vmx_vcpu_precreate(struct kvm *kvm)
  3946. {
  3947. return vmx_alloc_ipiv_pid_table(kvm);
  3948. }
  3949. #define VMX_XSS_EXIT_BITMAP 0
  3950. static void init_vmcs(struct vcpu_vmx *vmx)
  3951. {
  3952. struct kvm *kvm = vmx->vcpu.kvm;
  3953. struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
  3954. if (nested)
  3955. nested_vmx_set_vmcs_shadowing_bitmap();
  3956. if (cpu_has_vmx_msr_bitmap())
  3957. vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
  3958. vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
  3959. /* Control */
  3960. pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
  3961. exec_controls_set(vmx, vmx_exec_control(vmx));
  3962. if (cpu_has_secondary_exec_ctrls())
  3963. secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
  3964. if (cpu_has_tertiary_exec_ctrls())
  3965. tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
  3966. if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
  3967. vmcs_write64(EOI_EXIT_BITMAP0, 0);
  3968. vmcs_write64(EOI_EXIT_BITMAP1, 0);
  3969. vmcs_write64(EOI_EXIT_BITMAP2, 0);
  3970. vmcs_write64(EOI_EXIT_BITMAP3, 0);
  3971. vmcs_write16(GUEST_INTR_STATUS, 0);
  3972. vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
  3973. vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
  3974. }
  3975. if (vmx_can_use_ipiv(&vmx->vcpu)) {
  3976. vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
  3977. vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
  3978. }
  3979. if (!kvm_pause_in_guest(kvm)) {
  3980. vmcs_write32(PLE_GAP, ple_gap);
  3981. vmx->ple_window = ple_window;
  3982. vmx->ple_window_dirty = true;
  3983. }
  3984. if (kvm_notify_vmexit_enabled(kvm))
  3985. vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
  3986. vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
  3987. vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
  3988. vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
  3989. vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
  3990. vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
  3991. vmx_set_constant_host_state(vmx);
  3992. vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
  3993. vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
  3994. if (cpu_has_vmx_vmfunc())
  3995. vmcs_write64(VM_FUNCTION_CONTROL, 0);
  3996. vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
  3997. vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
  3998. vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
  3999. vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
  4000. vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
  4001. if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
  4002. vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
  4003. vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
  4004. /* 22.2.1, 20.8.1 */
  4005. vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
  4006. vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
  4007. vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
  4008. set_cr4_guest_host_mask(vmx);
  4009. if (vmx->vpid != 0)
  4010. vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
  4011. if (cpu_has_vmx_xsaves())
  4012. vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
  4013. if (enable_pml) {
  4014. vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
  4015. vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
  4016. }
  4017. vmx_write_encls_bitmap(&vmx->vcpu, NULL);
  4018. if (vmx_pt_mode_is_host_guest()) {
  4019. memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
  4020. /* Bit[6~0] are forced to 1, writes are ignored. */
  4021. vmx->pt_desc.guest.output_mask = 0x7F;
  4022. vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
  4023. }
  4024. vmcs_write32(GUEST_SYSENTER_CS, 0);
  4025. vmcs_writel(GUEST_SYSENTER_ESP, 0);
  4026. vmcs_writel(GUEST_SYSENTER_EIP, 0);
  4027. vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
  4028. if (cpu_has_vmx_tpr_shadow()) {
  4029. vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
  4030. if (cpu_need_tpr_shadow(&vmx->vcpu))
  4031. vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
  4032. __pa(vmx->vcpu.arch.apic->regs));
  4033. vmcs_write32(TPR_THRESHOLD, 0);
  4034. }
  4035. vmx_setup_uret_msrs(vmx);
  4036. }
  4037. static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
  4038. {
  4039. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4040. init_vmcs(vmx);
  4041. if (nested)
  4042. memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
  4043. vcpu_setup_sgx_lepubkeyhash(vcpu);
  4044. vmx->nested.posted_intr_nv = -1;
  4045. vmx->nested.vmxon_ptr = INVALID_GPA;
  4046. vmx->nested.current_vmptr = INVALID_GPA;
  4047. vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
  4048. vcpu->arch.microcode_version = 0x100000000ULL;
  4049. vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
  4050. /*
  4051. * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
  4052. * or POSTED_INTR_WAKEUP_VECTOR.
  4053. */
  4054. vmx->pi_desc.nv = POSTED_INTR_VECTOR;
  4055. vmx->pi_desc.sn = 1;
  4056. }
  4057. static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  4058. {
  4059. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4060. if (!init_event)
  4061. __vmx_vcpu_reset(vcpu);
  4062. vmx->rmode.vm86_active = 0;
  4063. vmx->spec_ctrl = 0;
  4064. vmx->msr_ia32_umwait_control = 0;
  4065. vmx->hv_deadline_tsc = -1;
  4066. kvm_set_cr8(vcpu, 0);
  4067. vmx_segment_cache_clear(vmx);
  4068. kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
  4069. seg_setup(VCPU_SREG_CS);
  4070. vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
  4071. vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
  4072. seg_setup(VCPU_SREG_DS);
  4073. seg_setup(VCPU_SREG_ES);
  4074. seg_setup(VCPU_SREG_FS);
  4075. seg_setup(VCPU_SREG_GS);
  4076. seg_setup(VCPU_SREG_SS);
  4077. vmcs_write16(GUEST_TR_SELECTOR, 0);
  4078. vmcs_writel(GUEST_TR_BASE, 0);
  4079. vmcs_write32(GUEST_TR_LIMIT, 0xffff);
  4080. vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
  4081. vmcs_write16(GUEST_LDTR_SELECTOR, 0);
  4082. vmcs_writel(GUEST_LDTR_BASE, 0);
  4083. vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
  4084. vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
  4085. vmcs_writel(GUEST_GDTR_BASE, 0);
  4086. vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
  4087. vmcs_writel(GUEST_IDTR_BASE, 0);
  4088. vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
  4089. vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
  4090. vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
  4091. vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
  4092. if (kvm_mpx_supported())
  4093. vmcs_write64(GUEST_BNDCFGS, 0);
  4094. vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
  4095. kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
  4096. vpid_sync_context(vmx->vpid);
  4097. vmx_update_fb_clear_dis(vcpu, vmx);
  4098. }
  4099. static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
  4100. {
  4101. exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
  4102. }
  4103. static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
  4104. {
  4105. if (!enable_vnmi ||
  4106. vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
  4107. vmx_enable_irq_window(vcpu);
  4108. return;
  4109. }
  4110. exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
  4111. }
  4112. static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
  4113. {
  4114. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4115. uint32_t intr;
  4116. int irq = vcpu->arch.interrupt.nr;
  4117. trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
  4118. ++vcpu->stat.irq_injections;
  4119. if (vmx->rmode.vm86_active) {
  4120. int inc_eip = 0;
  4121. if (vcpu->arch.interrupt.soft)
  4122. inc_eip = vcpu->arch.event_exit_inst_len;
  4123. kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
  4124. return;
  4125. }
  4126. intr = irq | INTR_INFO_VALID_MASK;
  4127. if (vcpu->arch.interrupt.soft) {
  4128. intr |= INTR_TYPE_SOFT_INTR;
  4129. vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
  4130. vmx->vcpu.arch.event_exit_inst_len);
  4131. } else
  4132. intr |= INTR_TYPE_EXT_INTR;
  4133. vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
  4134. vmx_clear_hlt(vcpu);
  4135. }
  4136. static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
  4137. {
  4138. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4139. if (!enable_vnmi) {
  4140. /*
  4141. * Tracking the NMI-blocked state in software is built upon
  4142. * finding the next open IRQ window. This, in turn, depends on
  4143. * well-behaving guests: They have to keep IRQs disabled at
  4144. * least as long as the NMI handler runs. Otherwise we may
  4145. * cause NMI nesting, maybe breaking the guest. But as this is
  4146. * highly unlikely, we can live with the residual risk.
  4147. */
  4148. vmx->loaded_vmcs->soft_vnmi_blocked = 1;
  4149. vmx->loaded_vmcs->vnmi_blocked_time = 0;
  4150. }
  4151. ++vcpu->stat.nmi_injections;
  4152. vmx->loaded_vmcs->nmi_known_unmasked = false;
  4153. if (vmx->rmode.vm86_active) {
  4154. kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
  4155. return;
  4156. }
  4157. vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
  4158. INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
  4159. vmx_clear_hlt(vcpu);
  4160. }
  4161. bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
  4162. {
  4163. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4164. bool masked;
  4165. if (!enable_vnmi)
  4166. return vmx->loaded_vmcs->soft_vnmi_blocked;
  4167. if (vmx->loaded_vmcs->nmi_known_unmasked)
  4168. return false;
  4169. masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
  4170. vmx->loaded_vmcs->nmi_known_unmasked = !masked;
  4171. return masked;
  4172. }
  4173. void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
  4174. {
  4175. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4176. if (!enable_vnmi) {
  4177. if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
  4178. vmx->loaded_vmcs->soft_vnmi_blocked = masked;
  4179. vmx->loaded_vmcs->vnmi_blocked_time = 0;
  4180. }
  4181. } else {
  4182. vmx->loaded_vmcs->nmi_known_unmasked = !masked;
  4183. if (masked)
  4184. vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
  4185. GUEST_INTR_STATE_NMI);
  4186. else
  4187. vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
  4188. GUEST_INTR_STATE_NMI);
  4189. }
  4190. }
  4191. bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
  4192. {
  4193. if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
  4194. return false;
  4195. if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
  4196. return true;
  4197. return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
  4198. (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
  4199. GUEST_INTR_STATE_NMI));
  4200. }
  4201. static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  4202. {
  4203. if (to_vmx(vcpu)->nested.nested_run_pending)
  4204. return -EBUSY;
  4205. /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
  4206. if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
  4207. return -EBUSY;
  4208. return !vmx_nmi_blocked(vcpu);
  4209. }
  4210. bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
  4211. {
  4212. if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
  4213. return false;
  4214. return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
  4215. (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
  4216. (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
  4217. }
  4218. static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  4219. {
  4220. if (to_vmx(vcpu)->nested.nested_run_pending)
  4221. return -EBUSY;
  4222. /*
  4223. * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
  4224. * e.g. if the IRQ arrived asynchronously after checking nested events.
  4225. */
  4226. if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
  4227. return -EBUSY;
  4228. return !vmx_interrupt_blocked(vcpu);
  4229. }
  4230. static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
  4231. {
  4232. void __user *ret;
  4233. if (enable_unrestricted_guest)
  4234. return 0;
  4235. mutex_lock(&kvm->slots_lock);
  4236. ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
  4237. PAGE_SIZE * 3);
  4238. mutex_unlock(&kvm->slots_lock);
  4239. if (IS_ERR(ret))
  4240. return PTR_ERR(ret);
  4241. to_kvm_vmx(kvm)->tss_addr = addr;
  4242. return init_rmode_tss(kvm, ret);
  4243. }
  4244. static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
  4245. {
  4246. to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
  4247. return 0;
  4248. }
  4249. static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
  4250. {
  4251. switch (vec) {
  4252. case BP_VECTOR:
  4253. /*
  4254. * Update instruction length as we may reinject the exception
  4255. * from user space while in guest debugging mode.
  4256. */
  4257. to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
  4258. vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
  4259. if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
  4260. return false;
  4261. fallthrough;
  4262. case DB_VECTOR:
  4263. return !(vcpu->guest_debug &
  4264. (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
  4265. case DE_VECTOR:
  4266. case OF_VECTOR:
  4267. case BR_VECTOR:
  4268. case UD_VECTOR:
  4269. case DF_VECTOR:
  4270. case SS_VECTOR:
  4271. case GP_VECTOR:
  4272. case MF_VECTOR:
  4273. return true;
  4274. }
  4275. return false;
  4276. }
  4277. static int handle_rmode_exception(struct kvm_vcpu *vcpu,
  4278. int vec, u32 err_code)
  4279. {
  4280. /*
  4281. * Instruction with address size override prefix opcode 0x67
  4282. * Cause the #SS fault with 0 error code in VM86 mode.
  4283. */
  4284. if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
  4285. if (kvm_emulate_instruction(vcpu, 0)) {
  4286. if (vcpu->arch.halt_request) {
  4287. vcpu->arch.halt_request = 0;
  4288. return kvm_emulate_halt_noskip(vcpu);
  4289. }
  4290. return 1;
  4291. }
  4292. return 0;
  4293. }
  4294. /*
  4295. * Forward all other exceptions that are valid in real mode.
  4296. * FIXME: Breaks guest debugging in real mode, needs to be fixed with
  4297. * the required debugging infrastructure rework.
  4298. */
  4299. kvm_queue_exception(vcpu, vec);
  4300. return 1;
  4301. }
  4302. static int handle_machine_check(struct kvm_vcpu *vcpu)
  4303. {
  4304. /* handled by vmx_vcpu_run() */
  4305. return 1;
  4306. }
  4307. /*
  4308. * If the host has split lock detection disabled, then #AC is
  4309. * unconditionally injected into the guest, which is the pre split lock
  4310. * detection behaviour.
  4311. *
  4312. * If the host has split lock detection enabled then #AC is
  4313. * only injected into the guest when:
  4314. * - Guest CPL == 3 (user mode)
  4315. * - Guest has #AC detection enabled in CR0
  4316. * - Guest EFLAGS has AC bit set
  4317. */
  4318. bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
  4319. {
  4320. if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
  4321. return true;
  4322. return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
  4323. (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
  4324. }
  4325. static int handle_exception_nmi(struct kvm_vcpu *vcpu)
  4326. {
  4327. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4328. struct kvm_run *kvm_run = vcpu->run;
  4329. u32 intr_info, ex_no, error_code;
  4330. unsigned long cr2, dr6;
  4331. u32 vect_info;
  4332. vect_info = vmx->idt_vectoring_info;
  4333. intr_info = vmx_get_intr_info(vcpu);
  4334. if (is_machine_check(intr_info) || is_nmi(intr_info))
  4335. return 1; /* handled by handle_exception_nmi_irqoff() */
  4336. /*
  4337. * Queue the exception here instead of in handle_nm_fault_irqoff().
  4338. * This ensures the nested_vmx check is not skipped so vmexit can
  4339. * be reflected to L1 (when it intercepts #NM) before reaching this
  4340. * point.
  4341. */
  4342. if (is_nm_fault(intr_info)) {
  4343. kvm_queue_exception(vcpu, NM_VECTOR);
  4344. return 1;
  4345. }
  4346. if (is_invalid_opcode(intr_info))
  4347. return handle_ud(vcpu);
  4348. error_code = 0;
  4349. if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
  4350. error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
  4351. if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
  4352. WARN_ON_ONCE(!enable_vmware_backdoor);
  4353. /*
  4354. * VMware backdoor emulation on #GP interception only handles
  4355. * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
  4356. * error code on #GP.
  4357. */
  4358. if (error_code) {
  4359. kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
  4360. return 1;
  4361. }
  4362. return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
  4363. }
  4364. /*
  4365. * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
  4366. * MMIO, it is better to report an internal error.
  4367. * See the comments in vmx_handle_exit.
  4368. */
  4369. if ((vect_info & VECTORING_INFO_VALID_MASK) &&
  4370. !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
  4371. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  4372. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
  4373. vcpu->run->internal.ndata = 4;
  4374. vcpu->run->internal.data[0] = vect_info;
  4375. vcpu->run->internal.data[1] = intr_info;
  4376. vcpu->run->internal.data[2] = error_code;
  4377. vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
  4378. return 0;
  4379. }
  4380. if (is_page_fault(intr_info)) {
  4381. cr2 = vmx_get_exit_qual(vcpu);
  4382. if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
  4383. /*
  4384. * EPT will cause page fault only if we need to
  4385. * detect illegal GPAs.
  4386. */
  4387. WARN_ON_ONCE(!allow_smaller_maxphyaddr);
  4388. kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
  4389. return 1;
  4390. } else
  4391. return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
  4392. }
  4393. ex_no = intr_info & INTR_INFO_VECTOR_MASK;
  4394. if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
  4395. return handle_rmode_exception(vcpu, ex_no, error_code);
  4396. switch (ex_no) {
  4397. case DB_VECTOR:
  4398. dr6 = vmx_get_exit_qual(vcpu);
  4399. if (!(vcpu->guest_debug &
  4400. (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
  4401. /*
  4402. * If the #DB was due to ICEBP, a.k.a. INT1, skip the
  4403. * instruction. ICEBP generates a trap-like #DB, but
  4404. * despite its interception control being tied to #DB,
  4405. * is an instruction intercept, i.e. the VM-Exit occurs
  4406. * on the ICEBP itself. Use the inner "skip" helper to
  4407. * avoid single-step #DB and MTF updates, as ICEBP is
  4408. * higher priority. Note, skipping ICEBP still clears
  4409. * STI and MOVSS blocking.
  4410. *
  4411. * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
  4412. * if single-step is enabled in RFLAGS and STI or MOVSS
  4413. * blocking is active, as the CPU doesn't set the bit
  4414. * on VM-Exit due to #DB interception. VM-Entry has a
  4415. * consistency check that a single-step #DB is pending
  4416. * in this scenario as the previous instruction cannot
  4417. * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
  4418. * don't modify RFLAGS), therefore the one instruction
  4419. * delay when activating single-step breakpoints must
  4420. * have already expired. Note, the CPU sets/clears BS
  4421. * as appropriate for all other VM-Exits types.
  4422. */
  4423. if (is_icebp(intr_info))
  4424. WARN_ON(!skip_emulated_instruction(vcpu));
  4425. else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
  4426. (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
  4427. (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
  4428. vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
  4429. vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
  4430. kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
  4431. return 1;
  4432. }
  4433. kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
  4434. kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
  4435. fallthrough;
  4436. case BP_VECTOR:
  4437. /*
  4438. * Update instruction length as we may reinject #BP from
  4439. * user space while in guest debugging mode. Reading it for
  4440. * #DB as well causes no harm, it is not used in that case.
  4441. */
  4442. vmx->vcpu.arch.event_exit_inst_len =
  4443. vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
  4444. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  4445. kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
  4446. kvm_run->debug.arch.exception = ex_no;
  4447. break;
  4448. case AC_VECTOR:
  4449. if (vmx_guest_inject_ac(vcpu)) {
  4450. kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
  4451. return 1;
  4452. }
  4453. /*
  4454. * Handle split lock. Depending on detection mode this will
  4455. * either warn and disable split lock detection for this
  4456. * task or force SIGBUS on it.
  4457. */
  4458. if (handle_guest_split_lock(kvm_rip_read(vcpu)))
  4459. return 1;
  4460. fallthrough;
  4461. default:
  4462. kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
  4463. kvm_run->ex.exception = ex_no;
  4464. kvm_run->ex.error_code = error_code;
  4465. break;
  4466. }
  4467. return 0;
  4468. }
  4469. static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
  4470. {
  4471. ++vcpu->stat.irq_exits;
  4472. return 1;
  4473. }
  4474. static int handle_triple_fault(struct kvm_vcpu *vcpu)
  4475. {
  4476. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  4477. vcpu->mmio_needed = 0;
  4478. return 0;
  4479. }
  4480. static int handle_io(struct kvm_vcpu *vcpu)
  4481. {
  4482. unsigned long exit_qualification;
  4483. int size, in, string;
  4484. unsigned port;
  4485. exit_qualification = vmx_get_exit_qual(vcpu);
  4486. string = (exit_qualification & 16) != 0;
  4487. ++vcpu->stat.io_exits;
  4488. if (string)
  4489. return kvm_emulate_instruction(vcpu, 0);
  4490. port = exit_qualification >> 16;
  4491. size = (exit_qualification & 7) + 1;
  4492. in = (exit_qualification & 8) != 0;
  4493. return kvm_fast_pio(vcpu, size, port, in);
  4494. }
  4495. static void
  4496. vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
  4497. {
  4498. /*
  4499. * Patch in the VMCALL instruction:
  4500. */
  4501. hypercall[0] = 0x0f;
  4502. hypercall[1] = 0x01;
  4503. hypercall[2] = 0xc1;
  4504. }
  4505. /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
  4506. static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
  4507. {
  4508. if (is_guest_mode(vcpu)) {
  4509. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  4510. unsigned long orig_val = val;
  4511. /*
  4512. * We get here when L2 changed cr0 in a way that did not change
  4513. * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
  4514. * but did change L0 shadowed bits. So we first calculate the
  4515. * effective cr0 value that L1 would like to write into the
  4516. * hardware. It consists of the L2-owned bits from the new
  4517. * value combined with the L1-owned bits from L1's guest_cr0.
  4518. */
  4519. val = (val & ~vmcs12->cr0_guest_host_mask) |
  4520. (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
  4521. if (kvm_set_cr0(vcpu, val))
  4522. return 1;
  4523. vmcs_writel(CR0_READ_SHADOW, orig_val);
  4524. return 0;
  4525. } else {
  4526. return kvm_set_cr0(vcpu, val);
  4527. }
  4528. }
  4529. static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
  4530. {
  4531. if (is_guest_mode(vcpu)) {
  4532. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  4533. unsigned long orig_val = val;
  4534. /* analogously to handle_set_cr0 */
  4535. val = (val & ~vmcs12->cr4_guest_host_mask) |
  4536. (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
  4537. if (kvm_set_cr4(vcpu, val))
  4538. return 1;
  4539. vmcs_writel(CR4_READ_SHADOW, orig_val);
  4540. return 0;
  4541. } else
  4542. return kvm_set_cr4(vcpu, val);
  4543. }
  4544. static int handle_desc(struct kvm_vcpu *vcpu)
  4545. {
  4546. WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
  4547. return kvm_emulate_instruction(vcpu, 0);
  4548. }
  4549. static int handle_cr(struct kvm_vcpu *vcpu)
  4550. {
  4551. unsigned long exit_qualification, val;
  4552. int cr;
  4553. int reg;
  4554. int err;
  4555. int ret;
  4556. exit_qualification = vmx_get_exit_qual(vcpu);
  4557. cr = exit_qualification & 15;
  4558. reg = (exit_qualification >> 8) & 15;
  4559. switch ((exit_qualification >> 4) & 3) {
  4560. case 0: /* mov to cr */
  4561. val = kvm_register_read(vcpu, reg);
  4562. trace_kvm_cr_write(cr, val);
  4563. switch (cr) {
  4564. case 0:
  4565. err = handle_set_cr0(vcpu, val);
  4566. return kvm_complete_insn_gp(vcpu, err);
  4567. case 3:
  4568. WARN_ON_ONCE(enable_unrestricted_guest);
  4569. err = kvm_set_cr3(vcpu, val);
  4570. return kvm_complete_insn_gp(vcpu, err);
  4571. case 4:
  4572. err = handle_set_cr4(vcpu, val);
  4573. return kvm_complete_insn_gp(vcpu, err);
  4574. case 8: {
  4575. u8 cr8_prev = kvm_get_cr8(vcpu);
  4576. u8 cr8 = (u8)val;
  4577. err = kvm_set_cr8(vcpu, cr8);
  4578. ret = kvm_complete_insn_gp(vcpu, err);
  4579. if (lapic_in_kernel(vcpu))
  4580. return ret;
  4581. if (cr8_prev <= cr8)
  4582. return ret;
  4583. /*
  4584. * TODO: we might be squashing a
  4585. * KVM_GUESTDBG_SINGLESTEP-triggered
  4586. * KVM_EXIT_DEBUG here.
  4587. */
  4588. vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
  4589. return 0;
  4590. }
  4591. }
  4592. break;
  4593. case 2: /* clts */
  4594. KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
  4595. return -EIO;
  4596. case 1: /*mov from cr*/
  4597. switch (cr) {
  4598. case 3:
  4599. WARN_ON_ONCE(enable_unrestricted_guest);
  4600. val = kvm_read_cr3(vcpu);
  4601. kvm_register_write(vcpu, reg, val);
  4602. trace_kvm_cr_read(cr, val);
  4603. return kvm_skip_emulated_instruction(vcpu);
  4604. case 8:
  4605. val = kvm_get_cr8(vcpu);
  4606. kvm_register_write(vcpu, reg, val);
  4607. trace_kvm_cr_read(cr, val);
  4608. return kvm_skip_emulated_instruction(vcpu);
  4609. }
  4610. break;
  4611. case 3: /* lmsw */
  4612. val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
  4613. trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
  4614. kvm_lmsw(vcpu, val);
  4615. return kvm_skip_emulated_instruction(vcpu);
  4616. default:
  4617. break;
  4618. }
  4619. vcpu->run->exit_reason = 0;
  4620. vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
  4621. (int)(exit_qualification >> 4) & 3, cr);
  4622. return 0;
  4623. }
  4624. static int handle_dr(struct kvm_vcpu *vcpu)
  4625. {
  4626. unsigned long exit_qualification;
  4627. int dr, dr7, reg;
  4628. int err = 1;
  4629. exit_qualification = vmx_get_exit_qual(vcpu);
  4630. dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
  4631. /* First, if DR does not exist, trigger UD */
  4632. if (!kvm_require_dr(vcpu, dr))
  4633. return 1;
  4634. if (vmx_get_cpl(vcpu) > 0)
  4635. goto out;
  4636. dr7 = vmcs_readl(GUEST_DR7);
  4637. if (dr7 & DR7_GD) {
  4638. /*
  4639. * As the vm-exit takes precedence over the debug trap, we
  4640. * need to emulate the latter, either for the host or the
  4641. * guest debugging itself.
  4642. */
  4643. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  4644. vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
  4645. vcpu->run->debug.arch.dr7 = dr7;
  4646. vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
  4647. vcpu->run->debug.arch.exception = DB_VECTOR;
  4648. vcpu->run->exit_reason = KVM_EXIT_DEBUG;
  4649. return 0;
  4650. } else {
  4651. kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
  4652. return 1;
  4653. }
  4654. }
  4655. if (vcpu->guest_debug == 0) {
  4656. exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
  4657. /*
  4658. * No more DR vmexits; force a reload of the debug registers
  4659. * and reenter on this instruction. The next vmexit will
  4660. * retrieve the full state of the debug registers.
  4661. */
  4662. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
  4663. return 1;
  4664. }
  4665. reg = DEBUG_REG_ACCESS_REG(exit_qualification);
  4666. if (exit_qualification & TYPE_MOV_FROM_DR) {
  4667. unsigned long val;
  4668. kvm_get_dr(vcpu, dr, &val);
  4669. kvm_register_write(vcpu, reg, val);
  4670. err = 0;
  4671. } else {
  4672. err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
  4673. }
  4674. out:
  4675. return kvm_complete_insn_gp(vcpu, err);
  4676. }
  4677. static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
  4678. {
  4679. get_debugreg(vcpu->arch.db[0], 0);
  4680. get_debugreg(vcpu->arch.db[1], 1);
  4681. get_debugreg(vcpu->arch.db[2], 2);
  4682. get_debugreg(vcpu->arch.db[3], 3);
  4683. get_debugreg(vcpu->arch.dr6, 6);
  4684. vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
  4685. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
  4686. exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
  4687. /*
  4688. * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
  4689. * a stale dr6 from the guest.
  4690. */
  4691. set_debugreg(DR6_RESERVED, 6);
  4692. }
  4693. static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
  4694. {
  4695. vmcs_writel(GUEST_DR7, val);
  4696. }
  4697. static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
  4698. {
  4699. kvm_apic_update_ppr(vcpu);
  4700. return 1;
  4701. }
  4702. static int handle_interrupt_window(struct kvm_vcpu *vcpu)
  4703. {
  4704. exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
  4705. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4706. ++vcpu->stat.irq_window_exits;
  4707. return 1;
  4708. }
  4709. static int handle_invlpg(struct kvm_vcpu *vcpu)
  4710. {
  4711. unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
  4712. kvm_mmu_invlpg(vcpu, exit_qualification);
  4713. return kvm_skip_emulated_instruction(vcpu);
  4714. }
  4715. static int handle_apic_access(struct kvm_vcpu *vcpu)
  4716. {
  4717. if (likely(fasteoi)) {
  4718. unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
  4719. int access_type, offset;
  4720. access_type = exit_qualification & APIC_ACCESS_TYPE;
  4721. offset = exit_qualification & APIC_ACCESS_OFFSET;
  4722. /*
  4723. * Sane guest uses MOV to write EOI, with written value
  4724. * not cared. So make a short-circuit here by avoiding
  4725. * heavy instruction emulation.
  4726. */
  4727. if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
  4728. (offset == APIC_EOI)) {
  4729. kvm_lapic_set_eoi(vcpu);
  4730. return kvm_skip_emulated_instruction(vcpu);
  4731. }
  4732. }
  4733. return kvm_emulate_instruction(vcpu, 0);
  4734. }
  4735. static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
  4736. {
  4737. unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
  4738. int vector = exit_qualification & 0xff;
  4739. /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
  4740. kvm_apic_set_eoi_accelerated(vcpu, vector);
  4741. return 1;
  4742. }
  4743. static int handle_apic_write(struct kvm_vcpu *vcpu)
  4744. {
  4745. unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
  4746. /*
  4747. * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
  4748. * hardware has done any necessary aliasing, offset adjustments, etc...
  4749. * for the access. I.e. the correct value has already been written to
  4750. * the vAPIC page for the correct 16-byte chunk. KVM needs only to
  4751. * retrieve the register value and emulate the access.
  4752. */
  4753. u32 offset = exit_qualification & 0xff0;
  4754. kvm_apic_write_nodecode(vcpu, offset);
  4755. return 1;
  4756. }
  4757. static int handle_task_switch(struct kvm_vcpu *vcpu)
  4758. {
  4759. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4760. unsigned long exit_qualification;
  4761. bool has_error_code = false;
  4762. u32 error_code = 0;
  4763. u16 tss_selector;
  4764. int reason, type, idt_v, idt_index;
  4765. idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
  4766. idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
  4767. type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
  4768. exit_qualification = vmx_get_exit_qual(vcpu);
  4769. reason = (u32)exit_qualification >> 30;
  4770. if (reason == TASK_SWITCH_GATE && idt_v) {
  4771. switch (type) {
  4772. case INTR_TYPE_NMI_INTR:
  4773. vcpu->arch.nmi_injected = false;
  4774. vmx_set_nmi_mask(vcpu, true);
  4775. break;
  4776. case INTR_TYPE_EXT_INTR:
  4777. case INTR_TYPE_SOFT_INTR:
  4778. kvm_clear_interrupt_queue(vcpu);
  4779. break;
  4780. case INTR_TYPE_HARD_EXCEPTION:
  4781. if (vmx->idt_vectoring_info &
  4782. VECTORING_INFO_DELIVER_CODE_MASK) {
  4783. has_error_code = true;
  4784. error_code =
  4785. vmcs_read32(IDT_VECTORING_ERROR_CODE);
  4786. }
  4787. fallthrough;
  4788. case INTR_TYPE_SOFT_EXCEPTION:
  4789. kvm_clear_exception_queue(vcpu);
  4790. break;
  4791. default:
  4792. break;
  4793. }
  4794. }
  4795. tss_selector = exit_qualification;
  4796. if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
  4797. type != INTR_TYPE_EXT_INTR &&
  4798. type != INTR_TYPE_NMI_INTR))
  4799. WARN_ON(!skip_emulated_instruction(vcpu));
  4800. /*
  4801. * TODO: What about debug traps on tss switch?
  4802. * Are we supposed to inject them and update dr6?
  4803. */
  4804. return kvm_task_switch(vcpu, tss_selector,
  4805. type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
  4806. reason, has_error_code, error_code);
  4807. }
  4808. static int handle_ept_violation(struct kvm_vcpu *vcpu)
  4809. {
  4810. unsigned long exit_qualification;
  4811. gpa_t gpa;
  4812. u64 error_code;
  4813. exit_qualification = vmx_get_exit_qual(vcpu);
  4814. /*
  4815. * EPT violation happened while executing iret from NMI,
  4816. * "blocked by NMI" bit has to be set before next VM entry.
  4817. * There are errata that may cause this bit to not be set:
  4818. * AAK134, BY25.
  4819. */
  4820. if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
  4821. enable_vnmi &&
  4822. (exit_qualification & INTR_INFO_UNBLOCK_NMI))
  4823. vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
  4824. gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
  4825. trace_kvm_page_fault(vcpu, gpa, exit_qualification);
  4826. /* Is it a read fault? */
  4827. error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
  4828. ? PFERR_USER_MASK : 0;
  4829. /* Is it a write fault? */
  4830. error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
  4831. ? PFERR_WRITE_MASK : 0;
  4832. /* Is it a fetch fault? */
  4833. error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
  4834. ? PFERR_FETCH_MASK : 0;
  4835. /* ept page table entry is present? */
  4836. error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
  4837. ? PFERR_PRESENT_MASK : 0;
  4838. error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
  4839. PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
  4840. vcpu->arch.exit_qualification = exit_qualification;
  4841. /*
  4842. * Check that the GPA doesn't exceed physical memory limits, as that is
  4843. * a guest page fault. We have to emulate the instruction here, because
  4844. * if the illegal address is that of a paging structure, then
  4845. * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
  4846. * would also use advanced VM-exit information for EPT violations to
  4847. * reconstruct the page fault error code.
  4848. */
  4849. if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
  4850. return kvm_emulate_instruction(vcpu, 0);
  4851. return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
  4852. }
  4853. static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
  4854. {
  4855. gpa_t gpa;
  4856. if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
  4857. return 1;
  4858. /*
  4859. * A nested guest cannot optimize MMIO vmexits, because we have an
  4860. * nGPA here instead of the required GPA.
  4861. */
  4862. gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
  4863. if (!is_guest_mode(vcpu) &&
  4864. !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
  4865. trace_kvm_fast_mmio(gpa);
  4866. return kvm_skip_emulated_instruction(vcpu);
  4867. }
  4868. return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
  4869. }
  4870. static int handle_nmi_window(struct kvm_vcpu *vcpu)
  4871. {
  4872. if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
  4873. return -EIO;
  4874. exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
  4875. ++vcpu->stat.nmi_window_exits;
  4876. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4877. return 1;
  4878. }
  4879. static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
  4880. {
  4881. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4882. return vmx->emulation_required && !vmx->rmode.vm86_active &&
  4883. (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
  4884. }
  4885. static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
  4886. {
  4887. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4888. bool intr_window_requested;
  4889. unsigned count = 130;
  4890. intr_window_requested = exec_controls_get(vmx) &
  4891. CPU_BASED_INTR_WINDOW_EXITING;
  4892. while (vmx->emulation_required && count-- != 0) {
  4893. if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
  4894. return handle_interrupt_window(&vmx->vcpu);
  4895. if (kvm_test_request(KVM_REQ_EVENT, vcpu))
  4896. return 1;
  4897. if (!kvm_emulate_instruction(vcpu, 0))
  4898. return 0;
  4899. if (vmx_emulation_required_with_pending_exception(vcpu)) {
  4900. kvm_prepare_emulation_failure_exit(vcpu);
  4901. return 0;
  4902. }
  4903. if (vcpu->arch.halt_request) {
  4904. vcpu->arch.halt_request = 0;
  4905. return kvm_emulate_halt_noskip(vcpu);
  4906. }
  4907. /*
  4908. * Note, return 1 and not 0, vcpu_run() will invoke
  4909. * xfer_to_guest_mode() which will create a proper return
  4910. * code.
  4911. */
  4912. if (__xfer_to_guest_mode_work_pending())
  4913. return 1;
  4914. }
  4915. return 1;
  4916. }
  4917. static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
  4918. {
  4919. if (vmx_emulation_required_with_pending_exception(vcpu)) {
  4920. kvm_prepare_emulation_failure_exit(vcpu);
  4921. return 0;
  4922. }
  4923. return 1;
  4924. }
  4925. static void grow_ple_window(struct kvm_vcpu *vcpu)
  4926. {
  4927. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4928. unsigned int old = vmx->ple_window;
  4929. vmx->ple_window = __grow_ple_window(old, ple_window,
  4930. ple_window_grow,
  4931. ple_window_max);
  4932. if (vmx->ple_window != old) {
  4933. vmx->ple_window_dirty = true;
  4934. trace_kvm_ple_window_update(vcpu->vcpu_id,
  4935. vmx->ple_window, old);
  4936. }
  4937. }
  4938. static void shrink_ple_window(struct kvm_vcpu *vcpu)
  4939. {
  4940. struct vcpu_vmx *vmx = to_vmx(vcpu);
  4941. unsigned int old = vmx->ple_window;
  4942. vmx->ple_window = __shrink_ple_window(old, ple_window,
  4943. ple_window_shrink,
  4944. ple_window);
  4945. if (vmx->ple_window != old) {
  4946. vmx->ple_window_dirty = true;
  4947. trace_kvm_ple_window_update(vcpu->vcpu_id,
  4948. vmx->ple_window, old);
  4949. }
  4950. }
  4951. /*
  4952. * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
  4953. * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
  4954. */
  4955. static int handle_pause(struct kvm_vcpu *vcpu)
  4956. {
  4957. if (!kvm_pause_in_guest(vcpu->kvm))
  4958. grow_ple_window(vcpu);
  4959. /*
  4960. * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
  4961. * VM-execution control is ignored if CPL > 0. OTOH, KVM
  4962. * never set PAUSE_EXITING and just set PLE if supported,
  4963. * so the vcpu must be CPL=0 if it gets a PAUSE exit.
  4964. */
  4965. kvm_vcpu_on_spin(vcpu, true);
  4966. return kvm_skip_emulated_instruction(vcpu);
  4967. }
  4968. static int handle_monitor_trap(struct kvm_vcpu *vcpu)
  4969. {
  4970. return 1;
  4971. }
  4972. static int handle_invpcid(struct kvm_vcpu *vcpu)
  4973. {
  4974. u32 vmx_instruction_info;
  4975. unsigned long type;
  4976. gva_t gva;
  4977. struct {
  4978. u64 pcid;
  4979. u64 gla;
  4980. } operand;
  4981. int gpr_index;
  4982. if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
  4983. kvm_queue_exception(vcpu, UD_VECTOR);
  4984. return 1;
  4985. }
  4986. vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
  4987. gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
  4988. type = kvm_register_read(vcpu, gpr_index);
  4989. /* According to the Intel instruction reference, the memory operand
  4990. * is read even if it isn't needed (e.g., for type==all)
  4991. */
  4992. if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
  4993. vmx_instruction_info, false,
  4994. sizeof(operand), &gva))
  4995. return 1;
  4996. return kvm_handle_invpcid(vcpu, type, gva);
  4997. }
  4998. static int handle_pml_full(struct kvm_vcpu *vcpu)
  4999. {
  5000. unsigned long exit_qualification;
  5001. trace_kvm_pml_full(vcpu->vcpu_id);
  5002. exit_qualification = vmx_get_exit_qual(vcpu);
  5003. /*
  5004. * PML buffer FULL happened while executing iret from NMI,
  5005. * "blocked by NMI" bit has to be set before next VM entry.
  5006. */
  5007. if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
  5008. enable_vnmi &&
  5009. (exit_qualification & INTR_INFO_UNBLOCK_NMI))
  5010. vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
  5011. GUEST_INTR_STATE_NMI);
  5012. /*
  5013. * PML buffer already flushed at beginning of VMEXIT. Nothing to do
  5014. * here.., and there's no userspace involvement needed for PML.
  5015. */
  5016. return 1;
  5017. }
  5018. static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
  5019. {
  5020. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5021. if (!vmx->req_immediate_exit &&
  5022. !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
  5023. kvm_lapic_expired_hv_timer(vcpu);
  5024. return EXIT_FASTPATH_REENTER_GUEST;
  5025. }
  5026. return EXIT_FASTPATH_NONE;
  5027. }
  5028. static int handle_preemption_timer(struct kvm_vcpu *vcpu)
  5029. {
  5030. handle_fastpath_preemption_timer(vcpu);
  5031. return 1;
  5032. }
  5033. /*
  5034. * When nested=0, all VMX instruction VM Exits filter here. The handlers
  5035. * are overwritten by nested_vmx_setup() when nested=1.
  5036. */
  5037. static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
  5038. {
  5039. kvm_queue_exception(vcpu, UD_VECTOR);
  5040. return 1;
  5041. }
  5042. #ifndef CONFIG_X86_SGX_KVM
  5043. static int handle_encls(struct kvm_vcpu *vcpu)
  5044. {
  5045. /*
  5046. * SGX virtualization is disabled. There is no software enable bit for
  5047. * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
  5048. * the guest from executing ENCLS (when SGX is supported by hardware).
  5049. */
  5050. kvm_queue_exception(vcpu, UD_VECTOR);
  5051. return 1;
  5052. }
  5053. #endif /* CONFIG_X86_SGX_KVM */
  5054. static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
  5055. {
  5056. /*
  5057. * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
  5058. * VM-Exits. Unconditionally set the flag here and leave the handling to
  5059. * vmx_handle_exit().
  5060. */
  5061. to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
  5062. return 1;
  5063. }
  5064. static int handle_notify(struct kvm_vcpu *vcpu)
  5065. {
  5066. unsigned long exit_qual = vmx_get_exit_qual(vcpu);
  5067. bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
  5068. ++vcpu->stat.notify_window_exits;
  5069. /*
  5070. * Notify VM exit happened while executing iret from NMI,
  5071. * "blocked by NMI" bit has to be set before next VM entry.
  5072. */
  5073. if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
  5074. vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
  5075. GUEST_INTR_STATE_NMI);
  5076. if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
  5077. context_invalid) {
  5078. vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
  5079. vcpu->run->notify.flags = context_invalid ?
  5080. KVM_NOTIFY_CONTEXT_INVALID : 0;
  5081. return 0;
  5082. }
  5083. return 1;
  5084. }
  5085. /*
  5086. * The exit handlers return 1 if the exit was handled fully and guest execution
  5087. * may resume. Otherwise they set the kvm_run parameter to indicate what needs
  5088. * to be done to userspace and return 0.
  5089. */
  5090. static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
  5091. [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
  5092. [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
  5093. [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
  5094. [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
  5095. [EXIT_REASON_IO_INSTRUCTION] = handle_io,
  5096. [EXIT_REASON_CR_ACCESS] = handle_cr,
  5097. [EXIT_REASON_DR_ACCESS] = handle_dr,
  5098. [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
  5099. [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
  5100. [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
  5101. [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
  5102. [EXIT_REASON_HLT] = kvm_emulate_halt,
  5103. [EXIT_REASON_INVD] = kvm_emulate_invd,
  5104. [EXIT_REASON_INVLPG] = handle_invlpg,
  5105. [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
  5106. [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
  5107. [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
  5108. [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
  5109. [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
  5110. [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
  5111. [EXIT_REASON_VMREAD] = handle_vmx_instruction,
  5112. [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
  5113. [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
  5114. [EXIT_REASON_VMOFF] = handle_vmx_instruction,
  5115. [EXIT_REASON_VMON] = handle_vmx_instruction,
  5116. [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
  5117. [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
  5118. [EXIT_REASON_APIC_WRITE] = handle_apic_write,
  5119. [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
  5120. [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
  5121. [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
  5122. [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
  5123. [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
  5124. [EXIT_REASON_GDTR_IDTR] = handle_desc,
  5125. [EXIT_REASON_LDTR_TR] = handle_desc,
  5126. [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
  5127. [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
  5128. [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
  5129. [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
  5130. [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
  5131. [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
  5132. [EXIT_REASON_INVEPT] = handle_vmx_instruction,
  5133. [EXIT_REASON_INVVPID] = handle_vmx_instruction,
  5134. [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
  5135. [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
  5136. [EXIT_REASON_PML_FULL] = handle_pml_full,
  5137. [EXIT_REASON_INVPCID] = handle_invpcid,
  5138. [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
  5139. [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
  5140. [EXIT_REASON_ENCLS] = handle_encls,
  5141. [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
  5142. [EXIT_REASON_NOTIFY] = handle_notify,
  5143. };
  5144. static const int kvm_vmx_max_exit_handlers =
  5145. ARRAY_SIZE(kvm_vmx_exit_handlers);
  5146. static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
  5147. u64 *info1, u64 *info2,
  5148. u32 *intr_info, u32 *error_code)
  5149. {
  5150. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5151. *reason = vmx->exit_reason.full;
  5152. *info1 = vmx_get_exit_qual(vcpu);
  5153. if (!(vmx->exit_reason.failed_vmentry)) {
  5154. *info2 = vmx->idt_vectoring_info;
  5155. *intr_info = vmx_get_intr_info(vcpu);
  5156. if (is_exception_with_error_code(*intr_info))
  5157. *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
  5158. else
  5159. *error_code = 0;
  5160. } else {
  5161. *info2 = 0;
  5162. *intr_info = 0;
  5163. *error_code = 0;
  5164. }
  5165. }
  5166. static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
  5167. {
  5168. if (vmx->pml_pg) {
  5169. __free_page(vmx->pml_pg);
  5170. vmx->pml_pg = NULL;
  5171. }
  5172. }
  5173. static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
  5174. {
  5175. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5176. u64 *pml_buf;
  5177. u16 pml_idx;
  5178. pml_idx = vmcs_read16(GUEST_PML_INDEX);
  5179. /* Do nothing if PML buffer is empty */
  5180. if (pml_idx == (PML_ENTITY_NUM - 1))
  5181. return;
  5182. /* PML index always points to next available PML buffer entity */
  5183. if (pml_idx >= PML_ENTITY_NUM)
  5184. pml_idx = 0;
  5185. else
  5186. pml_idx++;
  5187. pml_buf = page_address(vmx->pml_pg);
  5188. for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
  5189. u64 gpa;
  5190. gpa = pml_buf[pml_idx];
  5191. WARN_ON(gpa & (PAGE_SIZE - 1));
  5192. kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
  5193. }
  5194. /* reset PML index */
  5195. vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
  5196. }
  5197. static void vmx_dump_sel(char *name, uint32_t sel)
  5198. {
  5199. pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
  5200. name, vmcs_read16(sel),
  5201. vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
  5202. vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
  5203. vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
  5204. }
  5205. static void vmx_dump_dtsel(char *name, uint32_t limit)
  5206. {
  5207. pr_err("%s limit=0x%08x, base=0x%016lx\n",
  5208. name, vmcs_read32(limit),
  5209. vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
  5210. }
  5211. static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
  5212. {
  5213. unsigned int i;
  5214. struct vmx_msr_entry *e;
  5215. pr_err("MSR %s:\n", name);
  5216. for (i = 0, e = m->val; i < m->nr; ++i, ++e)
  5217. pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
  5218. }
  5219. void dump_vmcs(struct kvm_vcpu *vcpu)
  5220. {
  5221. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5222. u32 vmentry_ctl, vmexit_ctl;
  5223. u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
  5224. u64 tertiary_exec_control;
  5225. unsigned long cr4;
  5226. int efer_slot;
  5227. if (!dump_invalid_vmcs) {
  5228. pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
  5229. return;
  5230. }
  5231. vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
  5232. vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
  5233. cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
  5234. pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
  5235. cr4 = vmcs_readl(GUEST_CR4);
  5236. if (cpu_has_secondary_exec_ctrls())
  5237. secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
  5238. else
  5239. secondary_exec_control = 0;
  5240. if (cpu_has_tertiary_exec_ctrls())
  5241. tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
  5242. else
  5243. tertiary_exec_control = 0;
  5244. pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
  5245. vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
  5246. pr_err("*** Guest State ***\n");
  5247. pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
  5248. vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
  5249. vmcs_readl(CR0_GUEST_HOST_MASK));
  5250. pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
  5251. cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
  5252. pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
  5253. if (cpu_has_vmx_ept()) {
  5254. pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
  5255. vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
  5256. pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
  5257. vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
  5258. }
  5259. pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
  5260. vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
  5261. pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
  5262. vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
  5263. pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
  5264. vmcs_readl(GUEST_SYSENTER_ESP),
  5265. vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
  5266. vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
  5267. vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
  5268. vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
  5269. vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
  5270. vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
  5271. vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
  5272. vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
  5273. vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
  5274. vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
  5275. vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
  5276. efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
  5277. if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
  5278. pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
  5279. else if (efer_slot >= 0)
  5280. pr_err("EFER= 0x%016llx (autoload)\n",
  5281. vmx->msr_autoload.guest.val[efer_slot].value);
  5282. else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
  5283. pr_err("EFER= 0x%016llx (effective)\n",
  5284. vcpu->arch.efer | (EFER_LMA | EFER_LME));
  5285. else
  5286. pr_err("EFER= 0x%016llx (effective)\n",
  5287. vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
  5288. if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
  5289. pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
  5290. pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
  5291. vmcs_read64(GUEST_IA32_DEBUGCTL),
  5292. vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
  5293. if (cpu_has_load_perf_global_ctrl() &&
  5294. vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
  5295. pr_err("PerfGlobCtl = 0x%016llx\n",
  5296. vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
  5297. if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
  5298. pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
  5299. pr_err("Interruptibility = %08x ActivityState = %08x\n",
  5300. vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
  5301. vmcs_read32(GUEST_ACTIVITY_STATE));
  5302. if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
  5303. pr_err("InterruptStatus = %04x\n",
  5304. vmcs_read16(GUEST_INTR_STATUS));
  5305. if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
  5306. vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
  5307. if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
  5308. vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
  5309. pr_err("*** Host State ***\n");
  5310. pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
  5311. vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
  5312. pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
  5313. vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
  5314. vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
  5315. vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
  5316. vmcs_read16(HOST_TR_SELECTOR));
  5317. pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
  5318. vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
  5319. vmcs_readl(HOST_TR_BASE));
  5320. pr_err("GDTBase=%016lx IDTBase=%016lx\n",
  5321. vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
  5322. pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
  5323. vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
  5324. vmcs_readl(HOST_CR4));
  5325. pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
  5326. vmcs_readl(HOST_IA32_SYSENTER_ESP),
  5327. vmcs_read32(HOST_IA32_SYSENTER_CS),
  5328. vmcs_readl(HOST_IA32_SYSENTER_EIP));
  5329. if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
  5330. pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
  5331. if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
  5332. pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
  5333. if (cpu_has_load_perf_global_ctrl() &&
  5334. vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
  5335. pr_err("PerfGlobCtl = 0x%016llx\n",
  5336. vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
  5337. if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
  5338. vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
  5339. pr_err("*** Control State ***\n");
  5340. pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
  5341. cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
  5342. pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
  5343. pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
  5344. pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
  5345. vmcs_read32(EXCEPTION_BITMAP),
  5346. vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
  5347. vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
  5348. pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
  5349. vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
  5350. vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
  5351. vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
  5352. pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
  5353. vmcs_read32(VM_EXIT_INTR_INFO),
  5354. vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
  5355. vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
  5356. pr_err(" reason=%08x qualification=%016lx\n",
  5357. vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
  5358. pr_err("IDTVectoring: info=%08x errcode=%08x\n",
  5359. vmcs_read32(IDT_VECTORING_INFO_FIELD),
  5360. vmcs_read32(IDT_VECTORING_ERROR_CODE));
  5361. pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
  5362. if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
  5363. pr_err("TSC Multiplier = 0x%016llx\n",
  5364. vmcs_read64(TSC_MULTIPLIER));
  5365. if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
  5366. if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
  5367. u16 status = vmcs_read16(GUEST_INTR_STATUS);
  5368. pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
  5369. }
  5370. pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
  5371. if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
  5372. pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
  5373. pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
  5374. }
  5375. if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
  5376. pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
  5377. if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
  5378. pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
  5379. if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
  5380. pr_err("PLE Gap=%08x Window=%08x\n",
  5381. vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
  5382. if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
  5383. pr_err("Virtual processor ID = 0x%04x\n",
  5384. vmcs_read16(VIRTUAL_PROCESSOR_ID));
  5385. }
  5386. /*
  5387. * The guest has exited. See if we can fix it or if we need userspace
  5388. * assistance.
  5389. */
  5390. static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
  5391. {
  5392. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5393. union vmx_exit_reason exit_reason = vmx->exit_reason;
  5394. u32 vectoring_info = vmx->idt_vectoring_info;
  5395. u16 exit_handler_index;
  5396. /*
  5397. * Flush logged GPAs PML buffer, this will make dirty_bitmap more
  5398. * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
  5399. * querying dirty_bitmap, we only need to kick all vcpus out of guest
  5400. * mode as if vcpus is in root mode, the PML buffer must has been
  5401. * flushed already. Note, PML is never enabled in hardware while
  5402. * running L2.
  5403. */
  5404. if (enable_pml && !is_guest_mode(vcpu))
  5405. vmx_flush_pml_buffer(vcpu);
  5406. /*
  5407. * KVM should never reach this point with a pending nested VM-Enter.
  5408. * More specifically, short-circuiting VM-Entry to emulate L2 due to
  5409. * invalid guest state should never happen as that means KVM knowingly
  5410. * allowed a nested VM-Enter with an invalid vmcs12. More below.
  5411. */
  5412. if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
  5413. return -EIO;
  5414. if (is_guest_mode(vcpu)) {
  5415. /*
  5416. * PML is never enabled when running L2, bail immediately if a
  5417. * PML full exit occurs as something is horribly wrong.
  5418. */
  5419. if (exit_reason.basic == EXIT_REASON_PML_FULL)
  5420. goto unexpected_vmexit;
  5421. /*
  5422. * The host physical addresses of some pages of guest memory
  5423. * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
  5424. * Page). The CPU may write to these pages via their host
  5425. * physical address while L2 is running, bypassing any
  5426. * address-translation-based dirty tracking (e.g. EPT write
  5427. * protection).
  5428. *
  5429. * Mark them dirty on every exit from L2 to prevent them from
  5430. * getting out of sync with dirty tracking.
  5431. */
  5432. nested_mark_vmcs12_pages_dirty(vcpu);
  5433. /*
  5434. * Synthesize a triple fault if L2 state is invalid. In normal
  5435. * operation, nested VM-Enter rejects any attempt to enter L2
  5436. * with invalid state. However, those checks are skipped if
  5437. * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
  5438. * L2 state is invalid, it means either L1 modified SMRAM state
  5439. * or userspace provided bad state. Synthesize TRIPLE_FAULT as
  5440. * doing so is architecturally allowed in the RSM case, and is
  5441. * the least awful solution for the userspace case without
  5442. * risking false positives.
  5443. */
  5444. if (vmx->emulation_required) {
  5445. nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
  5446. return 1;
  5447. }
  5448. if (nested_vmx_reflect_vmexit(vcpu))
  5449. return 1;
  5450. }
  5451. /* If guest state is invalid, start emulating. L2 is handled above. */
  5452. if (vmx->emulation_required)
  5453. return handle_invalid_guest_state(vcpu);
  5454. if (exit_reason.failed_vmentry) {
  5455. dump_vmcs(vcpu);
  5456. vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
  5457. vcpu->run->fail_entry.hardware_entry_failure_reason
  5458. = exit_reason.full;
  5459. vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
  5460. return 0;
  5461. }
  5462. if (unlikely(vmx->fail)) {
  5463. dump_vmcs(vcpu);
  5464. vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
  5465. vcpu->run->fail_entry.hardware_entry_failure_reason
  5466. = vmcs_read32(VM_INSTRUCTION_ERROR);
  5467. vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
  5468. return 0;
  5469. }
  5470. /*
  5471. * Note:
  5472. * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
  5473. * delivery event since it indicates guest is accessing MMIO.
  5474. * The vm-exit can be triggered again after return to guest that
  5475. * will cause infinite loop.
  5476. */
  5477. if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
  5478. (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
  5479. exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
  5480. exit_reason.basic != EXIT_REASON_PML_FULL &&
  5481. exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
  5482. exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
  5483. exit_reason.basic != EXIT_REASON_NOTIFY)) {
  5484. int ndata = 3;
  5485. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  5486. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
  5487. vcpu->run->internal.data[0] = vectoring_info;
  5488. vcpu->run->internal.data[1] = exit_reason.full;
  5489. vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
  5490. if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
  5491. vcpu->run->internal.data[ndata++] =
  5492. vmcs_read64(GUEST_PHYSICAL_ADDRESS);
  5493. }
  5494. vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
  5495. vcpu->run->internal.ndata = ndata;
  5496. return 0;
  5497. }
  5498. if (unlikely(!enable_vnmi &&
  5499. vmx->loaded_vmcs->soft_vnmi_blocked)) {
  5500. if (!vmx_interrupt_blocked(vcpu)) {
  5501. vmx->loaded_vmcs->soft_vnmi_blocked = 0;
  5502. } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
  5503. vcpu->arch.nmi_pending) {
  5504. /*
  5505. * This CPU don't support us in finding the end of an
  5506. * NMI-blocked window if the guest runs with IRQs
  5507. * disabled. So we pull the trigger after 1 s of
  5508. * futile waiting, but inform the user about this.
  5509. */
  5510. printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
  5511. "state on VCPU %d after 1 s timeout\n",
  5512. __func__, vcpu->vcpu_id);
  5513. vmx->loaded_vmcs->soft_vnmi_blocked = 0;
  5514. }
  5515. }
  5516. if (exit_fastpath != EXIT_FASTPATH_NONE)
  5517. return 1;
  5518. if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
  5519. goto unexpected_vmexit;
  5520. #ifdef CONFIG_RETPOLINE
  5521. if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
  5522. return kvm_emulate_wrmsr(vcpu);
  5523. else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
  5524. return handle_preemption_timer(vcpu);
  5525. else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
  5526. return handle_interrupt_window(vcpu);
  5527. else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
  5528. return handle_external_interrupt(vcpu);
  5529. else if (exit_reason.basic == EXIT_REASON_HLT)
  5530. return kvm_emulate_halt(vcpu);
  5531. else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
  5532. return handle_ept_misconfig(vcpu);
  5533. #endif
  5534. exit_handler_index = array_index_nospec((u16)exit_reason.basic,
  5535. kvm_vmx_max_exit_handlers);
  5536. if (!kvm_vmx_exit_handlers[exit_handler_index])
  5537. goto unexpected_vmexit;
  5538. return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
  5539. unexpected_vmexit:
  5540. vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
  5541. exit_reason.full);
  5542. dump_vmcs(vcpu);
  5543. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  5544. vcpu->run->internal.suberror =
  5545. KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
  5546. vcpu->run->internal.ndata = 2;
  5547. vcpu->run->internal.data[0] = exit_reason.full;
  5548. vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
  5549. return 0;
  5550. }
  5551. static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
  5552. {
  5553. int ret = __vmx_handle_exit(vcpu, exit_fastpath);
  5554. /*
  5555. * Exit to user space when bus lock detected to inform that there is
  5556. * a bus lock in guest.
  5557. */
  5558. if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
  5559. if (ret > 0)
  5560. vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
  5561. vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
  5562. return 0;
  5563. }
  5564. return ret;
  5565. }
  5566. /*
  5567. * Software based L1D cache flush which is used when microcode providing
  5568. * the cache control MSR is not loaded.
  5569. *
  5570. * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
  5571. * flush it is required to read in 64 KiB because the replacement algorithm
  5572. * is not exactly LRU. This could be sized at runtime via topology
  5573. * information but as all relevant affected CPUs have 32KiB L1D cache size
  5574. * there is no point in doing so.
  5575. */
  5576. static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
  5577. {
  5578. int size = PAGE_SIZE << L1D_CACHE_ORDER;
  5579. /*
  5580. * This code is only executed when the flush mode is 'cond' or
  5581. * 'always'
  5582. */
  5583. if (static_branch_likely(&vmx_l1d_flush_cond)) {
  5584. bool flush_l1d;
  5585. /*
  5586. * Clear the per-vcpu flush bit, it gets set again
  5587. * either from vcpu_run() or from one of the unsafe
  5588. * VMEXIT handlers.
  5589. */
  5590. flush_l1d = vcpu->arch.l1tf_flush_l1d;
  5591. vcpu->arch.l1tf_flush_l1d = false;
  5592. /*
  5593. * Clear the per-cpu flush bit, it gets set again from
  5594. * the interrupt handlers.
  5595. */
  5596. flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
  5597. kvm_clear_cpu_l1tf_flush_l1d();
  5598. if (!flush_l1d)
  5599. return;
  5600. }
  5601. vcpu->stat.l1d_flush++;
  5602. if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
  5603. native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
  5604. return;
  5605. }
  5606. asm volatile(
  5607. /* First ensure the pages are in the TLB */
  5608. "xorl %%eax, %%eax\n"
  5609. ".Lpopulate_tlb:\n\t"
  5610. "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
  5611. "addl $4096, %%eax\n\t"
  5612. "cmpl %%eax, %[size]\n\t"
  5613. "jne .Lpopulate_tlb\n\t"
  5614. "xorl %%eax, %%eax\n\t"
  5615. "cpuid\n\t"
  5616. /* Now fill the cache */
  5617. "xorl %%eax, %%eax\n"
  5618. ".Lfill_cache:\n"
  5619. "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
  5620. "addl $64, %%eax\n\t"
  5621. "cmpl %%eax, %[size]\n\t"
  5622. "jne .Lfill_cache\n\t"
  5623. "lfence\n"
  5624. :: [flush_pages] "r" (vmx_l1d_flush_pages),
  5625. [size] "r" (size)
  5626. : "eax", "ebx", "ecx", "edx");
  5627. }
  5628. static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
  5629. {
  5630. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  5631. int tpr_threshold;
  5632. if (is_guest_mode(vcpu) &&
  5633. nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
  5634. return;
  5635. tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
  5636. if (is_guest_mode(vcpu))
  5637. to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
  5638. else
  5639. vmcs_write32(TPR_THRESHOLD, tpr_threshold);
  5640. }
  5641. void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
  5642. {
  5643. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5644. u32 sec_exec_control;
  5645. if (!lapic_in_kernel(vcpu))
  5646. return;
  5647. if (!flexpriority_enabled &&
  5648. !cpu_has_vmx_virtualize_x2apic_mode())
  5649. return;
  5650. /* Postpone execution until vmcs01 is the current VMCS. */
  5651. if (is_guest_mode(vcpu)) {
  5652. vmx->nested.change_vmcs01_virtual_apic_mode = true;
  5653. return;
  5654. }
  5655. sec_exec_control = secondary_exec_controls_get(vmx);
  5656. sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
  5657. SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
  5658. switch (kvm_get_apic_mode(vcpu)) {
  5659. case LAPIC_MODE_INVALID:
  5660. WARN_ONCE(true, "Invalid local APIC state");
  5661. break;
  5662. case LAPIC_MODE_DISABLED:
  5663. break;
  5664. case LAPIC_MODE_XAPIC:
  5665. if (flexpriority_enabled) {
  5666. sec_exec_control |=
  5667. SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
  5668. kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
  5669. /*
  5670. * Flush the TLB, reloading the APIC access page will
  5671. * only do so if its physical address has changed, but
  5672. * the guest may have inserted a non-APIC mapping into
  5673. * the TLB while the APIC access page was disabled.
  5674. */
  5675. kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
  5676. }
  5677. break;
  5678. case LAPIC_MODE_X2APIC:
  5679. if (cpu_has_vmx_virtualize_x2apic_mode())
  5680. sec_exec_control |=
  5681. SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
  5682. break;
  5683. }
  5684. secondary_exec_controls_set(vmx, sec_exec_control);
  5685. vmx_update_msr_bitmap_x2apic(vcpu);
  5686. }
  5687. static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
  5688. {
  5689. struct page *page;
  5690. /* Defer reload until vmcs01 is the current VMCS. */
  5691. if (is_guest_mode(vcpu)) {
  5692. to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
  5693. return;
  5694. }
  5695. if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
  5696. SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
  5697. return;
  5698. page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  5699. if (is_error_page(page))
  5700. return;
  5701. vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
  5702. vmx_flush_tlb_current(vcpu);
  5703. /*
  5704. * Do not pin apic access page in memory, the MMU notifier
  5705. * will call us again if it is migrated or swapped out.
  5706. */
  5707. put_page(page);
  5708. }
  5709. static void vmx_hwapic_isr_update(int max_isr)
  5710. {
  5711. u16 status;
  5712. u8 old;
  5713. if (max_isr == -1)
  5714. max_isr = 0;
  5715. status = vmcs_read16(GUEST_INTR_STATUS);
  5716. old = status >> 8;
  5717. if (max_isr != old) {
  5718. status &= 0xff;
  5719. status |= max_isr << 8;
  5720. vmcs_write16(GUEST_INTR_STATUS, status);
  5721. }
  5722. }
  5723. static void vmx_set_rvi(int vector)
  5724. {
  5725. u16 status;
  5726. u8 old;
  5727. if (vector == -1)
  5728. vector = 0;
  5729. status = vmcs_read16(GUEST_INTR_STATUS);
  5730. old = (u8)status & 0xff;
  5731. if ((u8)vector != old) {
  5732. status &= ~0xff;
  5733. status |= (u8)vector;
  5734. vmcs_write16(GUEST_INTR_STATUS, status);
  5735. }
  5736. }
  5737. static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
  5738. {
  5739. /*
  5740. * When running L2, updating RVI is only relevant when
  5741. * vmcs12 virtual-interrupt-delivery enabled.
  5742. * However, it can be enabled only when L1 also
  5743. * intercepts external-interrupts and in that case
  5744. * we should not update vmcs02 RVI but instead intercept
  5745. * interrupt. Therefore, do nothing when running L2.
  5746. */
  5747. if (!is_guest_mode(vcpu))
  5748. vmx_set_rvi(max_irr);
  5749. }
  5750. static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
  5751. {
  5752. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5753. int max_irr;
  5754. bool got_posted_interrupt;
  5755. if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
  5756. return -EIO;
  5757. if (pi_test_on(&vmx->pi_desc)) {
  5758. pi_clear_on(&vmx->pi_desc);
  5759. /*
  5760. * IOMMU can write to PID.ON, so the barrier matters even on UP.
  5761. * But on x86 this is just a compiler barrier anyway.
  5762. */
  5763. smp_mb__after_atomic();
  5764. got_posted_interrupt =
  5765. kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
  5766. } else {
  5767. max_irr = kvm_lapic_find_highest_irr(vcpu);
  5768. got_posted_interrupt = false;
  5769. }
  5770. /*
  5771. * Newly recognized interrupts are injected via either virtual interrupt
  5772. * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
  5773. * disabled in two cases:
  5774. *
  5775. * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
  5776. * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
  5777. * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
  5778. * into L2, but KVM doesn't use virtual interrupt delivery to inject
  5779. * interrupts into L2, and so KVM_REQ_EVENT is again needed.
  5780. *
  5781. * 2) If APICv is disabled for this vCPU, assigned devices may still
  5782. * attempt to post interrupts. The posted interrupt vector will cause
  5783. * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
  5784. */
  5785. if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
  5786. vmx_set_rvi(max_irr);
  5787. else if (got_posted_interrupt)
  5788. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5789. return max_irr;
  5790. }
  5791. static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
  5792. {
  5793. if (!kvm_vcpu_apicv_active(vcpu))
  5794. return;
  5795. vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
  5796. vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
  5797. vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
  5798. vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
  5799. }
  5800. static void vmx_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
  5801. {
  5802. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5803. pi_clear_on(&vmx->pi_desc);
  5804. memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
  5805. }
  5806. void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
  5807. static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
  5808. unsigned long entry)
  5809. {
  5810. bool is_nmi = entry == (unsigned long)asm_exc_nmi_noist;
  5811. kvm_before_interrupt(vcpu, is_nmi ? KVM_HANDLING_NMI : KVM_HANDLING_IRQ);
  5812. vmx_do_interrupt_nmi_irqoff(entry);
  5813. kvm_after_interrupt(vcpu);
  5814. }
  5815. static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
  5816. {
  5817. /*
  5818. * Save xfd_err to guest_fpu before interrupt is enabled, so the
  5819. * MSR value is not clobbered by the host activity before the guest
  5820. * has chance to consume it.
  5821. *
  5822. * Do not blindly read xfd_err here, since this exception might
  5823. * be caused by L1 interception on a platform which doesn't
  5824. * support xfd at all.
  5825. *
  5826. * Do it conditionally upon guest_fpu::xfd. xfd_err matters
  5827. * only when xfd contains a non-zero value.
  5828. *
  5829. * Queuing exception is done in vmx_handle_exit. See comment there.
  5830. */
  5831. if (vcpu->arch.guest_fpu.fpstate->xfd)
  5832. rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
  5833. }
  5834. static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
  5835. {
  5836. const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
  5837. u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
  5838. /* if exit due to PF check for async PF */
  5839. if (is_page_fault(intr_info))
  5840. vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
  5841. /* if exit due to NM, handle before interrupts are enabled */
  5842. else if (is_nm_fault(intr_info))
  5843. handle_nm_fault_irqoff(&vmx->vcpu);
  5844. /* Handle machine checks before interrupts are enabled */
  5845. else if (is_machine_check(intr_info))
  5846. kvm_machine_check();
  5847. /* We need to handle NMIs before interrupts are enabled */
  5848. else if (is_nmi(intr_info))
  5849. handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
  5850. }
  5851. static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
  5852. {
  5853. u32 intr_info = vmx_get_intr_info(vcpu);
  5854. unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
  5855. gate_desc *desc = (gate_desc *)host_idt_base + vector;
  5856. if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
  5857. "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
  5858. return;
  5859. handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
  5860. vcpu->arch.at_instruction_boundary = true;
  5861. }
  5862. static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
  5863. {
  5864. struct vcpu_vmx *vmx = to_vmx(vcpu);
  5865. if (vmx->emulation_required)
  5866. return;
  5867. if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
  5868. handle_external_interrupt_irqoff(vcpu);
  5869. else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
  5870. handle_exception_nmi_irqoff(vmx);
  5871. }
  5872. /*
  5873. * The kvm parameter can be NULL (module initialization, or invocation before
  5874. * VM creation). Be sure to check the kvm parameter before using it.
  5875. */
  5876. static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
  5877. {
  5878. switch (index) {
  5879. case MSR_IA32_SMBASE:
  5880. /*
  5881. * We cannot do SMM unless we can run the guest in big
  5882. * real mode.
  5883. */
  5884. return enable_unrestricted_guest || emulate_invalid_guest_state;
  5885. case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
  5886. return nested;
  5887. case MSR_AMD64_VIRT_SPEC_CTRL:
  5888. case MSR_AMD64_TSC_RATIO:
  5889. /* This is AMD only. */
  5890. return false;
  5891. default:
  5892. return true;
  5893. }
  5894. }
  5895. static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
  5896. {
  5897. u32 exit_intr_info;
  5898. bool unblock_nmi;
  5899. u8 vector;
  5900. bool idtv_info_valid;
  5901. idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
  5902. if (enable_vnmi) {
  5903. if (vmx->loaded_vmcs->nmi_known_unmasked)
  5904. return;
  5905. exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
  5906. unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
  5907. vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
  5908. /*
  5909. * SDM 3: 27.7.1.2 (September 2008)
  5910. * Re-set bit "block by NMI" before VM entry if vmexit caused by
  5911. * a guest IRET fault.
  5912. * SDM 3: 23.2.2 (September 2008)
  5913. * Bit 12 is undefined in any of the following cases:
  5914. * If the VM exit sets the valid bit in the IDT-vectoring
  5915. * information field.
  5916. * If the VM exit is due to a double fault.
  5917. */
  5918. if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
  5919. vector != DF_VECTOR && !idtv_info_valid)
  5920. vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
  5921. GUEST_INTR_STATE_NMI);
  5922. else
  5923. vmx->loaded_vmcs->nmi_known_unmasked =
  5924. !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
  5925. & GUEST_INTR_STATE_NMI);
  5926. } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
  5927. vmx->loaded_vmcs->vnmi_blocked_time +=
  5928. ktime_to_ns(ktime_sub(ktime_get(),
  5929. vmx->loaded_vmcs->entry_time));
  5930. }
  5931. static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
  5932. u32 idt_vectoring_info,
  5933. int instr_len_field,
  5934. int error_code_field)
  5935. {
  5936. u8 vector;
  5937. int type;
  5938. bool idtv_info_valid;
  5939. idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
  5940. vcpu->arch.nmi_injected = false;
  5941. kvm_clear_exception_queue(vcpu);
  5942. kvm_clear_interrupt_queue(vcpu);
  5943. if (!idtv_info_valid)
  5944. return;
  5945. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5946. vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
  5947. type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
  5948. switch (type) {
  5949. case INTR_TYPE_NMI_INTR:
  5950. vcpu->arch.nmi_injected = true;
  5951. /*
  5952. * SDM 3: 27.7.1.2 (September 2008)
  5953. * Clear bit "block by NMI" before VM entry if a NMI
  5954. * delivery faulted.
  5955. */
  5956. vmx_set_nmi_mask(vcpu, false);
  5957. break;
  5958. case INTR_TYPE_SOFT_EXCEPTION:
  5959. vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
  5960. fallthrough;
  5961. case INTR_TYPE_HARD_EXCEPTION:
  5962. if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
  5963. u32 err = vmcs_read32(error_code_field);
  5964. kvm_requeue_exception_e(vcpu, vector, err);
  5965. } else
  5966. kvm_requeue_exception(vcpu, vector);
  5967. break;
  5968. case INTR_TYPE_SOFT_INTR:
  5969. vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
  5970. fallthrough;
  5971. case INTR_TYPE_EXT_INTR:
  5972. kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
  5973. break;
  5974. default:
  5975. break;
  5976. }
  5977. }
  5978. static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
  5979. {
  5980. __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
  5981. VM_EXIT_INSTRUCTION_LEN,
  5982. IDT_VECTORING_ERROR_CODE);
  5983. }
  5984. static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
  5985. {
  5986. __vmx_complete_interrupts(vcpu,
  5987. vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
  5988. VM_ENTRY_INSTRUCTION_LEN,
  5989. VM_ENTRY_EXCEPTION_ERROR_CODE);
  5990. vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
  5991. }
  5992. static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
  5993. {
  5994. int i, nr_msrs;
  5995. struct perf_guest_switch_msr *msrs;
  5996. struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
  5997. pmu->host_cross_mapped_mask = 0;
  5998. if (pmu->pebs_enable & pmu->global_ctrl)
  5999. intel_pmu_cross_mapped_check(pmu);
  6000. /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
  6001. msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
  6002. if (!msrs)
  6003. return;
  6004. for (i = 0; i < nr_msrs; i++)
  6005. if (msrs[i].host == msrs[i].guest)
  6006. clear_atomic_switch_msr(vmx, msrs[i].msr);
  6007. else
  6008. add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
  6009. msrs[i].host, false);
  6010. }
  6011. static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
  6012. {
  6013. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6014. u64 tscl;
  6015. u32 delta_tsc;
  6016. if (vmx->req_immediate_exit) {
  6017. vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
  6018. vmx->loaded_vmcs->hv_timer_soft_disabled = false;
  6019. } else if (vmx->hv_deadline_tsc != -1) {
  6020. tscl = rdtsc();
  6021. if (vmx->hv_deadline_tsc > tscl)
  6022. /* set_hv_timer ensures the delta fits in 32-bits */
  6023. delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
  6024. cpu_preemption_timer_multi);
  6025. else
  6026. delta_tsc = 0;
  6027. vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
  6028. vmx->loaded_vmcs->hv_timer_soft_disabled = false;
  6029. } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
  6030. vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
  6031. vmx->loaded_vmcs->hv_timer_soft_disabled = true;
  6032. }
  6033. }
  6034. void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
  6035. {
  6036. if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
  6037. vmx->loaded_vmcs->host_state.rsp = host_rsp;
  6038. vmcs_writel(HOST_RSP, host_rsp);
  6039. }
  6040. }
  6041. void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
  6042. unsigned int flags)
  6043. {
  6044. u64 hostval = this_cpu_read(x86_spec_ctrl_current);
  6045. if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
  6046. return;
  6047. if (flags & VMX_RUN_SAVE_SPEC_CTRL)
  6048. vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
  6049. /*
  6050. * If the guest/host SPEC_CTRL values differ, restore the host value.
  6051. *
  6052. * For legacy IBRS, the IBRS bit always needs to be written after
  6053. * transitioning from a less privileged predictor mode, regardless of
  6054. * whether the guest/host values differ.
  6055. */
  6056. if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
  6057. vmx->spec_ctrl != hostval)
  6058. native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
  6059. barrier_nospec();
  6060. }
  6061. static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
  6062. {
  6063. switch (to_vmx(vcpu)->exit_reason.basic) {
  6064. case EXIT_REASON_MSR_WRITE:
  6065. return handle_fastpath_set_msr_irqoff(vcpu);
  6066. case EXIT_REASON_PREEMPTION_TIMER:
  6067. return handle_fastpath_preemption_timer(vcpu);
  6068. default:
  6069. return EXIT_FASTPATH_NONE;
  6070. }
  6071. }
  6072. static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
  6073. struct vcpu_vmx *vmx,
  6074. unsigned long flags)
  6075. {
  6076. guest_state_enter_irqoff();
  6077. /* L1D Flush includes CPU buffer clear to mitigate MDS */
  6078. if (static_branch_unlikely(&vmx_l1d_should_flush))
  6079. vmx_l1d_flush(vcpu);
  6080. else if (static_branch_unlikely(&mds_user_clear))
  6081. mds_clear_cpu_buffers();
  6082. else if (static_branch_unlikely(&mmio_stale_data_clear) &&
  6083. kvm_arch_has_assigned_device(vcpu->kvm))
  6084. mds_clear_cpu_buffers();
  6085. vmx_disable_fb_clear(vmx);
  6086. if (vcpu->arch.cr2 != native_read_cr2())
  6087. native_write_cr2(vcpu->arch.cr2);
  6088. vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
  6089. flags);
  6090. vcpu->arch.cr2 = native_read_cr2();
  6091. vmx_enable_fb_clear(vmx);
  6092. guest_state_exit_irqoff();
  6093. }
  6094. static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
  6095. {
  6096. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6097. unsigned long cr3, cr4;
  6098. /* Record the guest's net vcpu time for enforced NMI injections. */
  6099. if (unlikely(!enable_vnmi &&
  6100. vmx->loaded_vmcs->soft_vnmi_blocked))
  6101. vmx->loaded_vmcs->entry_time = ktime_get();
  6102. /*
  6103. * Don't enter VMX if guest state is invalid, let the exit handler
  6104. * start emulation until we arrive back to a valid state. Synthesize a
  6105. * consistency check VM-Exit due to invalid guest state and bail.
  6106. */
  6107. if (unlikely(vmx->emulation_required)) {
  6108. vmx->fail = 0;
  6109. vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
  6110. vmx->exit_reason.failed_vmentry = 1;
  6111. kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
  6112. vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
  6113. kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
  6114. vmx->exit_intr_info = 0;
  6115. return EXIT_FASTPATH_NONE;
  6116. }
  6117. trace_kvm_entry(vcpu);
  6118. if (vmx->ple_window_dirty) {
  6119. vmx->ple_window_dirty = false;
  6120. vmcs_write32(PLE_WINDOW, vmx->ple_window);
  6121. }
  6122. /*
  6123. * We did this in prepare_switch_to_guest, because it needs to
  6124. * be within srcu_read_lock.
  6125. */
  6126. WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
  6127. if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
  6128. vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
  6129. if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
  6130. vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
  6131. vcpu->arch.regs_dirty = 0;
  6132. /*
  6133. * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
  6134. * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
  6135. * it switches back to the current->mm, which can occur in KVM context
  6136. * when switching to a temporary mm to patch kernel code, e.g. if KVM
  6137. * toggles a static key while handling a VM-Exit.
  6138. */
  6139. cr3 = __get_current_cr3_fast();
  6140. if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
  6141. vmcs_writel(HOST_CR3, cr3);
  6142. vmx->loaded_vmcs->host_state.cr3 = cr3;
  6143. }
  6144. cr4 = cr4_read_shadow();
  6145. if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
  6146. vmcs_writel(HOST_CR4, cr4);
  6147. vmx->loaded_vmcs->host_state.cr4 = cr4;
  6148. }
  6149. /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
  6150. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
  6151. set_debugreg(vcpu->arch.dr6, 6);
  6152. /* When single-stepping over STI and MOV SS, we must clear the
  6153. * corresponding interruptibility bits in the guest state. Otherwise
  6154. * vmentry fails as it then expects bit 14 (BS) in pending debug
  6155. * exceptions being set, but that's not correct for the guest debugging
  6156. * case. */
  6157. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  6158. vmx_set_interrupt_shadow(vcpu, 0);
  6159. kvm_load_guest_xsave_state(vcpu);
  6160. pt_guest_enter(vmx);
  6161. atomic_switch_perf_msrs(vmx);
  6162. if (intel_pmu_lbr_is_enabled(vcpu))
  6163. vmx_passthrough_lbr_msrs(vcpu);
  6164. if (enable_preemption_timer)
  6165. vmx_update_hv_timer(vcpu);
  6166. kvm_wait_lapic_expire(vcpu);
  6167. /* The actual VMENTER/EXIT is in the .noinstr.text section. */
  6168. vmx_vcpu_enter_exit(vcpu, vmx, __vmx_vcpu_run_flags(vmx));
  6169. /* All fields are clean at this point */
  6170. if (static_branch_unlikely(&enable_evmcs)) {
  6171. current_evmcs->hv_clean_fields |=
  6172. HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
  6173. current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
  6174. }
  6175. /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
  6176. if (vmx->host_debugctlmsr)
  6177. update_debugctlmsr(vmx->host_debugctlmsr);
  6178. #ifndef CONFIG_X86_64
  6179. /*
  6180. * The sysexit path does not restore ds/es, so we must set them to
  6181. * a reasonable value ourselves.
  6182. *
  6183. * We can't defer this to vmx_prepare_switch_to_host() since that
  6184. * function may be executed in interrupt context, which saves and
  6185. * restore segments around it, nullifying its effect.
  6186. */
  6187. loadsegment(ds, __USER_DS);
  6188. loadsegment(es, __USER_DS);
  6189. #endif
  6190. vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
  6191. pt_guest_exit(vmx);
  6192. kvm_load_host_xsave_state(vcpu);
  6193. if (is_guest_mode(vcpu)) {
  6194. /*
  6195. * Track VMLAUNCH/VMRESUME that have made past guest state
  6196. * checking.
  6197. */
  6198. if (vmx->nested.nested_run_pending &&
  6199. !vmx->exit_reason.failed_vmentry)
  6200. ++vcpu->stat.nested_run;
  6201. vmx->nested.nested_run_pending = 0;
  6202. }
  6203. vmx->idt_vectoring_info = 0;
  6204. if (unlikely(vmx->fail)) {
  6205. vmx->exit_reason.full = 0xdead;
  6206. return EXIT_FASTPATH_NONE;
  6207. }
  6208. vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
  6209. if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
  6210. kvm_machine_check();
  6211. if (likely(!vmx->exit_reason.failed_vmentry))
  6212. vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
  6213. trace_kvm_exit(vcpu, KVM_ISA_VMX);
  6214. if (unlikely(vmx->exit_reason.failed_vmentry))
  6215. return EXIT_FASTPATH_NONE;
  6216. vmx->loaded_vmcs->launched = 1;
  6217. vmx_recover_nmi_blocking(vmx);
  6218. vmx_complete_interrupts(vmx);
  6219. if (is_guest_mode(vcpu))
  6220. return EXIT_FASTPATH_NONE;
  6221. return vmx_exit_handlers_fastpath(vcpu);
  6222. }
  6223. static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
  6224. {
  6225. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6226. if (enable_pml)
  6227. vmx_destroy_pml_buffer(vmx);
  6228. free_vpid(vmx->vpid);
  6229. nested_vmx_free_vcpu(vcpu);
  6230. free_loaded_vmcs(vmx->loaded_vmcs);
  6231. }
  6232. static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
  6233. {
  6234. struct vmx_uret_msr *tsx_ctrl;
  6235. struct vcpu_vmx *vmx;
  6236. int i, err;
  6237. BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
  6238. vmx = to_vmx(vcpu);
  6239. INIT_LIST_HEAD(&vmx->pi_wakeup_list);
  6240. err = -ENOMEM;
  6241. vmx->vpid = allocate_vpid();
  6242. /*
  6243. * If PML is turned on, failure on enabling PML just results in failure
  6244. * of creating the vcpu, therefore we can simplify PML logic (by
  6245. * avoiding dealing with cases, such as enabling PML partially on vcpus
  6246. * for the guest), etc.
  6247. */
  6248. if (enable_pml) {
  6249. vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
  6250. if (!vmx->pml_pg)
  6251. goto free_vpid;
  6252. }
  6253. for (i = 0; i < kvm_nr_uret_msrs; ++i)
  6254. vmx->guest_uret_msrs[i].mask = -1ull;
  6255. if (boot_cpu_has(X86_FEATURE_RTM)) {
  6256. /*
  6257. * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
  6258. * Keep the host value unchanged to avoid changing CPUID bits
  6259. * under the host kernel's feet.
  6260. */
  6261. tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
  6262. if (tsx_ctrl)
  6263. tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
  6264. }
  6265. err = alloc_loaded_vmcs(&vmx->vmcs01);
  6266. if (err < 0)
  6267. goto free_pml;
  6268. /*
  6269. * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
  6270. * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
  6271. * feature only for vmcs01, KVM currently isn't equipped to realize any
  6272. * performance benefits from enabling it for vmcs02.
  6273. */
  6274. if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs) &&
  6275. (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
  6276. struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
  6277. evmcs->hv_enlightenments_control.msr_bitmap = 1;
  6278. }
  6279. /* The MSR bitmap starts with all ones */
  6280. bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
  6281. bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
  6282. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
  6283. #ifdef CONFIG_X86_64
  6284. vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
  6285. vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
  6286. vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
  6287. #endif
  6288. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
  6289. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
  6290. vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
  6291. if (kvm_cstate_in_guest(vcpu->kvm)) {
  6292. vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
  6293. vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
  6294. vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
  6295. vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
  6296. }
  6297. vmx->loaded_vmcs = &vmx->vmcs01;
  6298. if (cpu_need_virtualize_apic_accesses(vcpu)) {
  6299. err = alloc_apic_access_page(vcpu->kvm);
  6300. if (err)
  6301. goto free_vmcs;
  6302. }
  6303. if (enable_ept && !enable_unrestricted_guest) {
  6304. err = init_rmode_identity_map(vcpu->kvm);
  6305. if (err)
  6306. goto free_vmcs;
  6307. }
  6308. if (vmx_can_use_ipiv(vcpu))
  6309. WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
  6310. __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
  6311. return 0;
  6312. free_vmcs:
  6313. free_loaded_vmcs(vmx->loaded_vmcs);
  6314. free_pml:
  6315. vmx_destroy_pml_buffer(vmx);
  6316. free_vpid:
  6317. free_vpid(vmx->vpid);
  6318. return err;
  6319. }
  6320. #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
  6321. #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
  6322. static int vmx_vm_init(struct kvm *kvm)
  6323. {
  6324. if (!ple_gap)
  6325. kvm->arch.pause_in_guest = true;
  6326. if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
  6327. switch (l1tf_mitigation) {
  6328. case L1TF_MITIGATION_OFF:
  6329. case L1TF_MITIGATION_FLUSH_NOWARN:
  6330. /* 'I explicitly don't care' is set */
  6331. break;
  6332. case L1TF_MITIGATION_FLUSH:
  6333. case L1TF_MITIGATION_FLUSH_NOSMT:
  6334. case L1TF_MITIGATION_FULL:
  6335. /*
  6336. * Warn upon starting the first VM in a potentially
  6337. * insecure environment.
  6338. */
  6339. if (sched_smt_active())
  6340. pr_warn_once(L1TF_MSG_SMT);
  6341. if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
  6342. pr_warn_once(L1TF_MSG_L1D);
  6343. break;
  6344. case L1TF_MITIGATION_FULL_FORCE:
  6345. /* Flush is enforced */
  6346. break;
  6347. }
  6348. }
  6349. return 0;
  6350. }
  6351. static int __init vmx_check_processor_compat(void)
  6352. {
  6353. struct vmcs_config vmcs_conf;
  6354. struct vmx_capability vmx_cap;
  6355. if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
  6356. !this_cpu_has(X86_FEATURE_VMX)) {
  6357. pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
  6358. return -EIO;
  6359. }
  6360. if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
  6361. return -EIO;
  6362. if (nested)
  6363. nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
  6364. if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
  6365. printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
  6366. smp_processor_id());
  6367. return -EIO;
  6368. }
  6369. return 0;
  6370. }
  6371. static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
  6372. {
  6373. u8 cache;
  6374. /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
  6375. * memory aliases with conflicting memory types and sometimes MCEs.
  6376. * We have to be careful as to what are honored and when.
  6377. *
  6378. * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
  6379. * UC. The effective memory type is UC or WC depending on guest PAT.
  6380. * This was historically the source of MCEs and we want to be
  6381. * conservative.
  6382. *
  6383. * When there is no need to deal with noncoherent DMA (e.g., no VT-d
  6384. * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
  6385. * EPT memory type is set to WB. The effective memory type is forced
  6386. * WB.
  6387. *
  6388. * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
  6389. * EPT memory type is used to emulate guest CD/MTRR.
  6390. */
  6391. if (is_mmio)
  6392. return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
  6393. if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
  6394. return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
  6395. if (kvm_read_cr0_bits(vcpu, X86_CR0_CD)) {
  6396. if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
  6397. cache = MTRR_TYPE_WRBACK;
  6398. else
  6399. cache = MTRR_TYPE_UNCACHABLE;
  6400. return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
  6401. }
  6402. return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
  6403. }
  6404. static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
  6405. {
  6406. /*
  6407. * These bits in the secondary execution controls field
  6408. * are dynamic, the others are mostly based on the hypervisor
  6409. * architecture and the guest's CPUID. Do not touch the
  6410. * dynamic bits.
  6411. */
  6412. u32 mask =
  6413. SECONDARY_EXEC_SHADOW_VMCS |
  6414. SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
  6415. SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
  6416. SECONDARY_EXEC_DESC;
  6417. u32 cur_ctl = secondary_exec_controls_get(vmx);
  6418. secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
  6419. }
  6420. /*
  6421. * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
  6422. * (indicating "allowed-1") if they are supported in the guest's CPUID.
  6423. */
  6424. static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
  6425. {
  6426. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6427. struct kvm_cpuid_entry2 *entry;
  6428. vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
  6429. vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
  6430. #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
  6431. if (entry && (entry->_reg & (_cpuid_mask))) \
  6432. vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
  6433. } while (0)
  6434. entry = kvm_find_cpuid_entry(vcpu, 0x1);
  6435. cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
  6436. cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
  6437. cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
  6438. cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
  6439. cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
  6440. cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
  6441. cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
  6442. cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
  6443. cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
  6444. cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
  6445. cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
  6446. cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
  6447. cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
  6448. cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
  6449. entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
  6450. cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
  6451. cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
  6452. cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
  6453. cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
  6454. cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
  6455. cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
  6456. #undef cr4_fixed1_update
  6457. }
  6458. static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
  6459. {
  6460. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6461. struct kvm_cpuid_entry2 *best = NULL;
  6462. int i;
  6463. for (i = 0; i < PT_CPUID_LEAVES; i++) {
  6464. best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
  6465. if (!best)
  6466. return;
  6467. vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
  6468. vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
  6469. vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
  6470. vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
  6471. }
  6472. /* Get the number of configurable Address Ranges for filtering */
  6473. vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
  6474. PT_CAP_num_address_ranges);
  6475. /* Initialize and clear the no dependency bits */
  6476. vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
  6477. RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
  6478. RTIT_CTL_BRANCH_EN);
  6479. /*
  6480. * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
  6481. * will inject an #GP
  6482. */
  6483. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
  6484. vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
  6485. /*
  6486. * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
  6487. * PSBFreq can be set
  6488. */
  6489. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
  6490. vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
  6491. RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
  6492. /*
  6493. * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
  6494. */
  6495. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
  6496. vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
  6497. RTIT_CTL_MTC_RANGE);
  6498. /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
  6499. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
  6500. vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
  6501. RTIT_CTL_PTW_EN);
  6502. /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
  6503. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
  6504. vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
  6505. /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
  6506. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
  6507. vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
  6508. /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
  6509. if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
  6510. vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
  6511. /* unmask address range configure area */
  6512. for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
  6513. vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
  6514. }
  6515. static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
  6516. {
  6517. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6518. /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
  6519. vcpu->arch.xsaves_enabled = false;
  6520. vmx_setup_uret_msrs(vmx);
  6521. if (cpu_has_secondary_exec_ctrls())
  6522. vmcs_set_secondary_exec_control(vmx,
  6523. vmx_secondary_exec_control(vmx));
  6524. if (nested_vmx_allowed(vcpu))
  6525. vmx->msr_ia32_feature_control_valid_bits |=
  6526. FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
  6527. FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
  6528. else
  6529. vmx->msr_ia32_feature_control_valid_bits &=
  6530. ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
  6531. FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
  6532. if (nested_vmx_allowed(vcpu))
  6533. nested_vmx_cr_fixed1_bits_update(vcpu);
  6534. if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
  6535. guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
  6536. update_intel_pt_cfg(vcpu);
  6537. if (boot_cpu_has(X86_FEATURE_RTM)) {
  6538. struct vmx_uret_msr *msr;
  6539. msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
  6540. if (msr) {
  6541. bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
  6542. vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
  6543. }
  6544. }
  6545. if (kvm_cpu_cap_has(X86_FEATURE_XFD))
  6546. vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
  6547. !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
  6548. set_cr4_guest_host_mask(vmx);
  6549. vmx_write_encls_bitmap(vcpu, NULL);
  6550. if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
  6551. vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
  6552. else
  6553. vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
  6554. if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
  6555. vmx->msr_ia32_feature_control_valid_bits |=
  6556. FEAT_CTL_SGX_LC_ENABLED;
  6557. else
  6558. vmx->msr_ia32_feature_control_valid_bits &=
  6559. ~FEAT_CTL_SGX_LC_ENABLED;
  6560. /* Refresh #PF interception to account for MAXPHYADDR changes. */
  6561. vmx_update_exception_bitmap(vcpu);
  6562. }
  6563. static u64 vmx_get_perf_capabilities(void)
  6564. {
  6565. u64 perf_cap = PMU_CAP_FW_WRITES;
  6566. struct x86_pmu_lbr lbr;
  6567. u64 host_perf_cap = 0;
  6568. if (!enable_pmu)
  6569. return 0;
  6570. if (boot_cpu_has(X86_FEATURE_PDCM))
  6571. rdmsrl(MSR_IA32_PERF_CAPABILITIES, host_perf_cap);
  6572. if (!cpu_feature_enabled(X86_FEATURE_ARCH_LBR)) {
  6573. x86_perf_get_lbr(&lbr);
  6574. if (lbr.nr)
  6575. perf_cap |= host_perf_cap & PMU_CAP_LBR_FMT;
  6576. }
  6577. if (vmx_pebs_supported()) {
  6578. perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK;
  6579. if ((perf_cap & PERF_CAP_PEBS_FORMAT) < 4)
  6580. perf_cap &= ~PERF_CAP_PEBS_BASELINE;
  6581. }
  6582. return perf_cap;
  6583. }
  6584. static __init void vmx_set_cpu_caps(void)
  6585. {
  6586. kvm_set_cpu_caps();
  6587. /* CPUID 0x1 */
  6588. if (nested)
  6589. kvm_cpu_cap_set(X86_FEATURE_VMX);
  6590. /* CPUID 0x7 */
  6591. if (kvm_mpx_supported())
  6592. kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
  6593. if (!cpu_has_vmx_invpcid())
  6594. kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
  6595. if (vmx_pt_mode_is_host_guest())
  6596. kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
  6597. if (vmx_pebs_supported()) {
  6598. kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
  6599. kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
  6600. }
  6601. if (!enable_pmu)
  6602. kvm_cpu_cap_clear(X86_FEATURE_PDCM);
  6603. kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
  6604. if (!enable_sgx) {
  6605. kvm_cpu_cap_clear(X86_FEATURE_SGX);
  6606. kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
  6607. kvm_cpu_cap_clear(X86_FEATURE_SGX1);
  6608. kvm_cpu_cap_clear(X86_FEATURE_SGX2);
  6609. }
  6610. if (vmx_umip_emulated())
  6611. kvm_cpu_cap_set(X86_FEATURE_UMIP);
  6612. /* CPUID 0xD.1 */
  6613. kvm_caps.supported_xss = 0;
  6614. if (!cpu_has_vmx_xsaves())
  6615. kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
  6616. /* CPUID 0x80000001 and 0x7 (RDPID) */
  6617. if (!cpu_has_vmx_rdtscp()) {
  6618. kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
  6619. kvm_cpu_cap_clear(X86_FEATURE_RDPID);
  6620. }
  6621. if (cpu_has_vmx_waitpkg())
  6622. kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
  6623. }
  6624. static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
  6625. {
  6626. to_vmx(vcpu)->req_immediate_exit = true;
  6627. }
  6628. static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
  6629. struct x86_instruction_info *info)
  6630. {
  6631. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  6632. unsigned short port;
  6633. bool intercept;
  6634. int size;
  6635. if (info->intercept == x86_intercept_in ||
  6636. info->intercept == x86_intercept_ins) {
  6637. port = info->src_val;
  6638. size = info->dst_bytes;
  6639. } else {
  6640. port = info->dst_val;
  6641. size = info->src_bytes;
  6642. }
  6643. /*
  6644. * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
  6645. * VM-exits depend on the 'unconditional IO exiting' VM-execution
  6646. * control.
  6647. *
  6648. * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
  6649. */
  6650. if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
  6651. intercept = nested_cpu_has(vmcs12,
  6652. CPU_BASED_UNCOND_IO_EXITING);
  6653. else
  6654. intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
  6655. /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
  6656. return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
  6657. }
  6658. static int vmx_check_intercept(struct kvm_vcpu *vcpu,
  6659. struct x86_instruction_info *info,
  6660. enum x86_intercept_stage stage,
  6661. struct x86_exception *exception)
  6662. {
  6663. struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  6664. switch (info->intercept) {
  6665. /*
  6666. * RDPID causes #UD if disabled through secondary execution controls.
  6667. * Because it is marked as EmulateOnUD, we need to intercept it here.
  6668. * Note, RDPID is hidden behind ENABLE_RDTSCP.
  6669. */
  6670. case x86_intercept_rdpid:
  6671. if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
  6672. exception->vector = UD_VECTOR;
  6673. exception->error_code_valid = false;
  6674. return X86EMUL_PROPAGATE_FAULT;
  6675. }
  6676. break;
  6677. case x86_intercept_in:
  6678. case x86_intercept_ins:
  6679. case x86_intercept_out:
  6680. case x86_intercept_outs:
  6681. return vmx_check_intercept_io(vcpu, info);
  6682. case x86_intercept_lgdt:
  6683. case x86_intercept_lidt:
  6684. case x86_intercept_lldt:
  6685. case x86_intercept_ltr:
  6686. case x86_intercept_sgdt:
  6687. case x86_intercept_sidt:
  6688. case x86_intercept_sldt:
  6689. case x86_intercept_str:
  6690. if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
  6691. return X86EMUL_CONTINUE;
  6692. /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
  6693. break;
  6694. case x86_intercept_pause:
  6695. /*
  6696. * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides
  6697. * with vanilla NOPs in the emulator. Apply the interception
  6698. * check only to actual PAUSE instructions. Don't check
  6699. * PAUSE-loop-exiting, software can't expect a given PAUSE to
  6700. * exit, i.e. KVM is within its rights to allow L2 to execute
  6701. * the PAUSE.
  6702. */
  6703. if ((info->rep_prefix != REPE_PREFIX) ||
  6704. !nested_cpu_has2(vmcs12, CPU_BASED_PAUSE_EXITING))
  6705. return X86EMUL_CONTINUE;
  6706. break;
  6707. /* TODO: check more intercepts... */
  6708. default:
  6709. break;
  6710. }
  6711. return X86EMUL_UNHANDLEABLE;
  6712. }
  6713. #ifdef CONFIG_X86_64
  6714. /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
  6715. static inline int u64_shl_div_u64(u64 a, unsigned int shift,
  6716. u64 divisor, u64 *result)
  6717. {
  6718. u64 low = a << shift, high = a >> (64 - shift);
  6719. /* To avoid the overflow on divq */
  6720. if (high >= divisor)
  6721. return 1;
  6722. /* Low hold the result, high hold rem which is discarded */
  6723. asm("divq %2\n\t" : "=a" (low), "=d" (high) :
  6724. "rm" (divisor), "0" (low), "1" (high));
  6725. *result = low;
  6726. return 0;
  6727. }
  6728. static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
  6729. bool *expired)
  6730. {
  6731. struct vcpu_vmx *vmx;
  6732. u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
  6733. struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
  6734. vmx = to_vmx(vcpu);
  6735. tscl = rdtsc();
  6736. guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
  6737. delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
  6738. lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
  6739. ktimer->timer_advance_ns);
  6740. if (delta_tsc > lapic_timer_advance_cycles)
  6741. delta_tsc -= lapic_timer_advance_cycles;
  6742. else
  6743. delta_tsc = 0;
  6744. /* Convert to host delta tsc if tsc scaling is enabled */
  6745. if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
  6746. delta_tsc && u64_shl_div_u64(delta_tsc,
  6747. kvm_caps.tsc_scaling_ratio_frac_bits,
  6748. vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
  6749. return -ERANGE;
  6750. /*
  6751. * If the delta tsc can't fit in the 32 bit after the multi shift,
  6752. * we can't use the preemption timer.
  6753. * It's possible that it fits on later vmentries, but checking
  6754. * on every vmentry is costly so we just use an hrtimer.
  6755. */
  6756. if (delta_tsc >> (cpu_preemption_timer_multi + 32))
  6757. return -ERANGE;
  6758. vmx->hv_deadline_tsc = tscl + delta_tsc;
  6759. *expired = !delta_tsc;
  6760. return 0;
  6761. }
  6762. static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
  6763. {
  6764. to_vmx(vcpu)->hv_deadline_tsc = -1;
  6765. }
  6766. #endif
  6767. static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
  6768. {
  6769. if (!kvm_pause_in_guest(vcpu->kvm))
  6770. shrink_ple_window(vcpu);
  6771. }
  6772. void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
  6773. {
  6774. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6775. if (is_guest_mode(vcpu)) {
  6776. vmx->nested.update_vmcs01_cpu_dirty_logging = true;
  6777. return;
  6778. }
  6779. /*
  6780. * Note, cpu_dirty_logging_count can be changed concurrent with this
  6781. * code, but in that case another update request will be made and so
  6782. * the guest will never run with a stale PML value.
  6783. */
  6784. if (vcpu->kvm->arch.cpu_dirty_logging_count)
  6785. secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
  6786. else
  6787. secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
  6788. }
  6789. static void vmx_setup_mce(struct kvm_vcpu *vcpu)
  6790. {
  6791. if (vcpu->arch.mcg_cap & MCG_LMCE_P)
  6792. to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
  6793. FEAT_CTL_LMCE_ENABLED;
  6794. else
  6795. to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
  6796. ~FEAT_CTL_LMCE_ENABLED;
  6797. }
  6798. static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
  6799. {
  6800. /* we need a nested vmexit to enter SMM, postpone if run is pending */
  6801. if (to_vmx(vcpu)->nested.nested_run_pending)
  6802. return -EBUSY;
  6803. return !is_smm(vcpu);
  6804. }
  6805. static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
  6806. {
  6807. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6808. /*
  6809. * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
  6810. * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
  6811. * SMI and RSM only modify state that is saved and restored via SMRAM.
  6812. * E.g. most MSRs are left untouched, but many are modified by VM-Exit
  6813. * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
  6814. */
  6815. vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
  6816. if (vmx->nested.smm.guest_mode)
  6817. nested_vmx_vmexit(vcpu, -1, 0, 0);
  6818. vmx->nested.smm.vmxon = vmx->nested.vmxon;
  6819. vmx->nested.vmxon = false;
  6820. vmx_clear_hlt(vcpu);
  6821. return 0;
  6822. }
  6823. static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
  6824. {
  6825. struct vcpu_vmx *vmx = to_vmx(vcpu);
  6826. int ret;
  6827. if (vmx->nested.smm.vmxon) {
  6828. vmx->nested.vmxon = true;
  6829. vmx->nested.smm.vmxon = false;
  6830. }
  6831. if (vmx->nested.smm.guest_mode) {
  6832. ret = nested_vmx_enter_non_root_mode(vcpu, false);
  6833. if (ret)
  6834. return ret;
  6835. vmx->nested.nested_run_pending = 1;
  6836. vmx->nested.smm.guest_mode = false;
  6837. }
  6838. return 0;
  6839. }
  6840. static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
  6841. {
  6842. /* RSM will cause a vmexit anyway. */
  6843. }
  6844. static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
  6845. {
  6846. return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
  6847. }
  6848. static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
  6849. {
  6850. if (is_guest_mode(vcpu)) {
  6851. struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
  6852. if (hrtimer_try_to_cancel(timer) == 1)
  6853. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  6854. }
  6855. }
  6856. static void vmx_hardware_unsetup(void)
  6857. {
  6858. kvm_set_posted_intr_wakeup_handler(NULL);
  6859. if (nested)
  6860. nested_vmx_hardware_unsetup();
  6861. free_kvm_area();
  6862. }
  6863. static bool vmx_check_apicv_inhibit_reasons(enum kvm_apicv_inhibit reason)
  6864. {
  6865. ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
  6866. BIT(APICV_INHIBIT_REASON_ABSENT) |
  6867. BIT(APICV_INHIBIT_REASON_HYPERV) |
  6868. BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |
  6869. BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |
  6870. BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
  6871. return supported & BIT(reason);
  6872. }
  6873. static void vmx_vm_destroy(struct kvm *kvm)
  6874. {
  6875. struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
  6876. free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
  6877. }
  6878. static struct kvm_x86_ops vmx_x86_ops __initdata = {
  6879. .name = "kvm_intel",
  6880. .hardware_unsetup = vmx_hardware_unsetup,
  6881. .hardware_enable = vmx_hardware_enable,
  6882. .hardware_disable = vmx_hardware_disable,
  6883. .has_emulated_msr = vmx_has_emulated_msr,
  6884. .vm_size = sizeof(struct kvm_vmx),
  6885. .vm_init = vmx_vm_init,
  6886. .vm_destroy = vmx_vm_destroy,
  6887. .vcpu_precreate = vmx_vcpu_precreate,
  6888. .vcpu_create = vmx_vcpu_create,
  6889. .vcpu_free = vmx_vcpu_free,
  6890. .vcpu_reset = vmx_vcpu_reset,
  6891. .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
  6892. .vcpu_load = vmx_vcpu_load,
  6893. .vcpu_put = vmx_vcpu_put,
  6894. .update_exception_bitmap = vmx_update_exception_bitmap,
  6895. .get_msr_feature = vmx_get_msr_feature,
  6896. .get_msr = vmx_get_msr,
  6897. .set_msr = vmx_set_msr,
  6898. .get_segment_base = vmx_get_segment_base,
  6899. .get_segment = vmx_get_segment,
  6900. .set_segment = vmx_set_segment,
  6901. .get_cpl = vmx_get_cpl,
  6902. .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
  6903. .is_valid_cr0 = vmx_is_valid_cr0,
  6904. .set_cr0 = vmx_set_cr0,
  6905. .is_valid_cr4 = vmx_is_valid_cr4,
  6906. .set_cr4 = vmx_set_cr4,
  6907. .set_efer = vmx_set_efer,
  6908. .get_idt = vmx_get_idt,
  6909. .set_idt = vmx_set_idt,
  6910. .get_gdt = vmx_get_gdt,
  6911. .set_gdt = vmx_set_gdt,
  6912. .set_dr7 = vmx_set_dr7,
  6913. .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
  6914. .cache_reg = vmx_cache_reg,
  6915. .get_rflags = vmx_get_rflags,
  6916. .set_rflags = vmx_set_rflags,
  6917. .get_if_flag = vmx_get_if_flag,
  6918. .flush_tlb_all = vmx_flush_tlb_all,
  6919. .flush_tlb_current = vmx_flush_tlb_current,
  6920. .flush_tlb_gva = vmx_flush_tlb_gva,
  6921. .flush_tlb_guest = vmx_flush_tlb_guest,
  6922. .vcpu_pre_run = vmx_vcpu_pre_run,
  6923. .vcpu_run = vmx_vcpu_run,
  6924. .handle_exit = vmx_handle_exit,
  6925. .skip_emulated_instruction = vmx_skip_emulated_instruction,
  6926. .update_emulated_instruction = vmx_update_emulated_instruction,
  6927. .set_interrupt_shadow = vmx_set_interrupt_shadow,
  6928. .get_interrupt_shadow = vmx_get_interrupt_shadow,
  6929. .patch_hypercall = vmx_patch_hypercall,
  6930. .inject_irq = vmx_inject_irq,
  6931. .inject_nmi = vmx_inject_nmi,
  6932. .inject_exception = vmx_inject_exception,
  6933. .cancel_injection = vmx_cancel_injection,
  6934. .interrupt_allowed = vmx_interrupt_allowed,
  6935. .nmi_allowed = vmx_nmi_allowed,
  6936. .get_nmi_mask = vmx_get_nmi_mask,
  6937. .set_nmi_mask = vmx_set_nmi_mask,
  6938. .enable_nmi_window = vmx_enable_nmi_window,
  6939. .enable_irq_window = vmx_enable_irq_window,
  6940. .update_cr8_intercept = vmx_update_cr8_intercept,
  6941. .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
  6942. .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
  6943. .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
  6944. .load_eoi_exitmap = vmx_load_eoi_exitmap,
  6945. .apicv_pre_state_restore = vmx_apicv_pre_state_restore,
  6946. .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
  6947. .hwapic_irr_update = vmx_hwapic_irr_update,
  6948. .hwapic_isr_update = vmx_hwapic_isr_update,
  6949. .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
  6950. .sync_pir_to_irr = vmx_sync_pir_to_irr,
  6951. .deliver_interrupt = vmx_deliver_interrupt,
  6952. .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
  6953. .set_tss_addr = vmx_set_tss_addr,
  6954. .set_identity_map_addr = vmx_set_identity_map_addr,
  6955. .get_mt_mask = vmx_get_mt_mask,
  6956. .get_exit_info = vmx_get_exit_info,
  6957. .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
  6958. .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
  6959. .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
  6960. .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
  6961. .write_tsc_offset = vmx_write_tsc_offset,
  6962. .write_tsc_multiplier = vmx_write_tsc_multiplier,
  6963. .load_mmu_pgd = vmx_load_mmu_pgd,
  6964. .check_intercept = vmx_check_intercept,
  6965. .handle_exit_irqoff = vmx_handle_exit_irqoff,
  6966. .request_immediate_exit = vmx_request_immediate_exit,
  6967. .sched_in = vmx_sched_in,
  6968. .cpu_dirty_log_size = PML_ENTITY_NUM,
  6969. .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
  6970. .nested_ops = &vmx_nested_ops,
  6971. .pi_update_irte = vmx_pi_update_irte,
  6972. .pi_start_assignment = vmx_pi_start_assignment,
  6973. #ifdef CONFIG_X86_64
  6974. .set_hv_timer = vmx_set_hv_timer,
  6975. .cancel_hv_timer = vmx_cancel_hv_timer,
  6976. #endif
  6977. .setup_mce = vmx_setup_mce,
  6978. .smi_allowed = vmx_smi_allowed,
  6979. .enter_smm = vmx_enter_smm,
  6980. .leave_smm = vmx_leave_smm,
  6981. .enable_smi_window = vmx_enable_smi_window,
  6982. .can_emulate_instruction = vmx_can_emulate_instruction,
  6983. .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
  6984. .migrate_timers = vmx_migrate_timers,
  6985. .msr_filter_changed = vmx_msr_filter_changed,
  6986. .complete_emulated_msr = kvm_complete_insn_gp,
  6987. .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
  6988. };
  6989. static unsigned int vmx_handle_intel_pt_intr(void)
  6990. {
  6991. struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
  6992. /* '0' on failure so that the !PT case can use a RET0 static call. */
  6993. if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
  6994. return 0;
  6995. kvm_make_request(KVM_REQ_PMI, vcpu);
  6996. __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
  6997. (unsigned long *)&vcpu->arch.pmu.global_status);
  6998. return 1;
  6999. }
  7000. static __init void vmx_setup_user_return_msrs(void)
  7001. {
  7002. /*
  7003. * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
  7004. * will emulate SYSCALL in legacy mode if the vendor string in guest
  7005. * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
  7006. * support this emulation, MSR_STAR is included in the list for i386,
  7007. * but is never loaded into hardware. MSR_CSTAR is also never loaded
  7008. * into hardware and is here purely for emulation purposes.
  7009. */
  7010. const u32 vmx_uret_msrs_list[] = {
  7011. #ifdef CONFIG_X86_64
  7012. MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
  7013. #endif
  7014. MSR_EFER, MSR_TSC_AUX, MSR_STAR,
  7015. MSR_IA32_TSX_CTRL,
  7016. };
  7017. int i;
  7018. BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
  7019. for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
  7020. kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
  7021. }
  7022. static void __init vmx_setup_me_spte_mask(void)
  7023. {
  7024. u64 me_mask = 0;
  7025. /*
  7026. * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
  7027. * the former to avoid exposing shadow_phys_bits.
  7028. *
  7029. * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
  7030. * shadow_phys_bits. On MKTME and/or TDX capable systems,
  7031. * boot_cpu_data.x86_phys_bits holds the actual physical address
  7032. * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
  7033. * reported by CPUID. Those bits between are KeyID bits.
  7034. */
  7035. if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
  7036. me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
  7037. kvm_get_shadow_phys_bits() - 1);
  7038. /*
  7039. * Unlike SME, host kernel doesn't support setting up any
  7040. * MKTME KeyID on Intel platforms. No memory encryption
  7041. * bits should be included into the SPTE.
  7042. */
  7043. kvm_mmu_set_me_spte_mask(0, me_mask);
  7044. }
  7045. static struct kvm_x86_init_ops vmx_init_ops __initdata;
  7046. static __init int hardware_setup(void)
  7047. {
  7048. unsigned long host_bndcfgs;
  7049. struct desc_ptr dt;
  7050. int r;
  7051. store_idt(&dt);
  7052. host_idt_base = dt.address;
  7053. vmx_setup_user_return_msrs();
  7054. if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
  7055. return -EIO;
  7056. if (cpu_has_perf_global_ctrl_bug())
  7057. pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
  7058. "does not work properly. Using workaround\n");
  7059. if (boot_cpu_has(X86_FEATURE_NX))
  7060. kvm_enable_efer_bits(EFER_NX);
  7061. if (boot_cpu_has(X86_FEATURE_MPX)) {
  7062. rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
  7063. WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
  7064. }
  7065. if (!cpu_has_vmx_mpx())
  7066. kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
  7067. XFEATURE_MASK_BNDCSR);
  7068. if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
  7069. !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
  7070. enable_vpid = 0;
  7071. if (!cpu_has_vmx_ept() ||
  7072. !cpu_has_vmx_ept_4levels() ||
  7073. !cpu_has_vmx_ept_mt_wb() ||
  7074. !cpu_has_vmx_invept_global())
  7075. enable_ept = 0;
  7076. /* NX support is required for shadow paging. */
  7077. if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
  7078. pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
  7079. return -EOPNOTSUPP;
  7080. }
  7081. if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
  7082. enable_ept_ad_bits = 0;
  7083. if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
  7084. enable_unrestricted_guest = 0;
  7085. if (!cpu_has_vmx_flexpriority())
  7086. flexpriority_enabled = 0;
  7087. if (!cpu_has_virtual_nmis())
  7088. enable_vnmi = 0;
  7089. #ifdef CONFIG_X86_SGX_KVM
  7090. if (!cpu_has_vmx_encls_vmexit())
  7091. enable_sgx = false;
  7092. #endif
  7093. /*
  7094. * set_apic_access_page_addr() is used to reload apic access
  7095. * page upon invalidation. No need to do anything if not
  7096. * using the APIC_ACCESS_ADDR VMCS field.
  7097. */
  7098. if (!flexpriority_enabled)
  7099. vmx_x86_ops.set_apic_access_page_addr = NULL;
  7100. if (!cpu_has_vmx_tpr_shadow())
  7101. vmx_x86_ops.update_cr8_intercept = NULL;
  7102. #if IS_ENABLED(CONFIG_HYPERV)
  7103. if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
  7104. && enable_ept) {
  7105. vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
  7106. vmx_x86_ops.tlb_remote_flush_with_range =
  7107. hv_remote_flush_tlb_with_range;
  7108. }
  7109. #endif
  7110. if (!cpu_has_vmx_ple()) {
  7111. ple_gap = 0;
  7112. ple_window = 0;
  7113. ple_window_grow = 0;
  7114. ple_window_max = 0;
  7115. ple_window_shrink = 0;
  7116. }
  7117. if (!cpu_has_vmx_apicv())
  7118. enable_apicv = 0;
  7119. if (!enable_apicv)
  7120. vmx_x86_ops.sync_pir_to_irr = NULL;
  7121. if (!enable_apicv || !cpu_has_vmx_ipiv())
  7122. enable_ipiv = false;
  7123. if (cpu_has_vmx_tsc_scaling())
  7124. kvm_caps.has_tsc_control = true;
  7125. kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
  7126. kvm_caps.tsc_scaling_ratio_frac_bits = 48;
  7127. kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
  7128. kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
  7129. set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
  7130. if (enable_ept)
  7131. kvm_mmu_set_ept_masks(enable_ept_ad_bits,
  7132. cpu_has_vmx_ept_execute_only());
  7133. /*
  7134. * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
  7135. * bits to shadow_zero_check.
  7136. */
  7137. vmx_setup_me_spte_mask();
  7138. kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
  7139. ept_caps_to_lpage_level(vmx_capability.ept));
  7140. /*
  7141. * Only enable PML when hardware supports PML feature, and both EPT
  7142. * and EPT A/D bit features are enabled -- PML depends on them to work.
  7143. */
  7144. if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
  7145. enable_pml = 0;
  7146. if (!enable_pml)
  7147. vmx_x86_ops.cpu_dirty_log_size = 0;
  7148. if (!cpu_has_vmx_preemption_timer())
  7149. enable_preemption_timer = false;
  7150. if (enable_preemption_timer) {
  7151. u64 use_timer_freq = 5000ULL * 1000 * 1000;
  7152. cpu_preemption_timer_multi =
  7153. vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
  7154. if (tsc_khz)
  7155. use_timer_freq = (u64)tsc_khz * 1000;
  7156. use_timer_freq >>= cpu_preemption_timer_multi;
  7157. /*
  7158. * KVM "disables" the preemption timer by setting it to its max
  7159. * value. Don't use the timer if it might cause spurious exits
  7160. * at a rate faster than 0.1 Hz (of uninterrupted guest time).
  7161. */
  7162. if (use_timer_freq > 0xffffffffu / 10)
  7163. enable_preemption_timer = false;
  7164. }
  7165. if (!enable_preemption_timer) {
  7166. vmx_x86_ops.set_hv_timer = NULL;
  7167. vmx_x86_ops.cancel_hv_timer = NULL;
  7168. vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
  7169. }
  7170. kvm_caps.supported_mce_cap |= MCG_LMCE_P;
  7171. kvm_caps.supported_mce_cap |= MCG_CMCI_P;
  7172. if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
  7173. return -EINVAL;
  7174. if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
  7175. pt_mode = PT_MODE_SYSTEM;
  7176. if (pt_mode == PT_MODE_HOST_GUEST)
  7177. vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
  7178. else
  7179. vmx_init_ops.handle_intel_pt_intr = NULL;
  7180. setup_default_sgx_lepubkeyhash();
  7181. if (nested) {
  7182. nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
  7183. r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
  7184. if (r)
  7185. return r;
  7186. }
  7187. vmx_set_cpu_caps();
  7188. r = alloc_kvm_area();
  7189. if (r && nested)
  7190. nested_vmx_hardware_unsetup();
  7191. kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
  7192. return r;
  7193. }
  7194. static struct kvm_x86_init_ops vmx_init_ops __initdata = {
  7195. .cpu_has_kvm_support = cpu_has_kvm_support,
  7196. .disabled_by_bios = vmx_disabled_by_bios,
  7197. .check_processor_compatibility = vmx_check_processor_compat,
  7198. .hardware_setup = hardware_setup,
  7199. .handle_intel_pt_intr = NULL,
  7200. .runtime_ops = &vmx_x86_ops,
  7201. .pmu_ops = &intel_pmu_ops,
  7202. };
  7203. static void vmx_cleanup_l1d_flush(void)
  7204. {
  7205. if (vmx_l1d_flush_pages) {
  7206. free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
  7207. vmx_l1d_flush_pages = NULL;
  7208. }
  7209. /* Restore state so sysfs ignores VMX */
  7210. l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
  7211. }
  7212. static void __vmx_exit(void)
  7213. {
  7214. allow_smaller_maxphyaddr = false;
  7215. RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
  7216. synchronize_rcu();
  7217. vmx_cleanup_l1d_flush();
  7218. }
  7219. static void vmx_exit(void)
  7220. {
  7221. kvm_exit();
  7222. kvm_x86_vendor_exit();
  7223. __vmx_exit();
  7224. }
  7225. module_exit(vmx_exit);
  7226. static int __init vmx_init(void)
  7227. {
  7228. int r, cpu;
  7229. #if IS_ENABLED(CONFIG_HYPERV)
  7230. /*
  7231. * Enlightened VMCS usage should be recommended and the host needs
  7232. * to support eVMCS v1 or above. We can also disable eVMCS support
  7233. * with module parameter.
  7234. */
  7235. if (enlightened_vmcs &&
  7236. ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
  7237. (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
  7238. KVM_EVMCS_VERSION) {
  7239. /* Check that we have assist pages on all online CPUs */
  7240. for_each_online_cpu(cpu) {
  7241. if (!hv_get_vp_assist_page(cpu)) {
  7242. enlightened_vmcs = false;
  7243. break;
  7244. }
  7245. }
  7246. if (enlightened_vmcs) {
  7247. pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
  7248. static_branch_enable(&enable_evmcs);
  7249. }
  7250. if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
  7251. vmx_x86_ops.enable_direct_tlbflush
  7252. = hv_enable_direct_tlbflush;
  7253. } else {
  7254. enlightened_vmcs = false;
  7255. }
  7256. #endif
  7257. r = kvm_x86_vendor_init(&vmx_init_ops);
  7258. if (r)
  7259. return r;
  7260. /*
  7261. * Must be called after common x86 init so enable_ept is properly set
  7262. * up. Hand the parameter mitigation value in which was stored in
  7263. * the pre module init parser. If no parameter was given, it will
  7264. * contain 'auto' which will be turned into the default 'cond'
  7265. * mitigation mode.
  7266. */
  7267. r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
  7268. if (r)
  7269. goto err_l1d_flush;
  7270. vmx_setup_fb_clear_ctrl();
  7271. for_each_possible_cpu(cpu) {
  7272. INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
  7273. pi_init_cpu(cpu);
  7274. }
  7275. rcu_assign_pointer(crash_vmclear_loaded_vmcss,
  7276. crash_vmclear_local_loaded_vmcss);
  7277. vmx_check_vmcs12_offsets();
  7278. /*
  7279. * Shadow paging doesn't have a (further) performance penalty
  7280. * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
  7281. * by default
  7282. */
  7283. if (!enable_ept)
  7284. allow_smaller_maxphyaddr = true;
  7285. /*
  7286. * Common KVM initialization _must_ come last, after this, /dev/kvm is
  7287. * exposed to userspace!
  7288. */
  7289. r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
  7290. __alignof__(struct vcpu_vmx), THIS_MODULE);
  7291. if (r)
  7292. goto err_kvm_init;
  7293. return 0;
  7294. err_kvm_init:
  7295. __vmx_exit();
  7296. err_l1d_flush:
  7297. kvm_x86_vendor_exit();
  7298. return r;
  7299. }
  7300. module_init(vmx_init);