x86.c 244 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516
  1. /*
  2. * Kernel-based Virtual Machine driver for Linux
  3. *
  4. * derived from drivers/kvm/kvm_main.c
  5. *
  6. * Copyright (C) 2006 Qumranet, Inc.
  7. * Copyright (C) 2008 Qumranet, Inc.
  8. * Copyright IBM Corporation, 2008
  9. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  10. *
  11. * Authors:
  12. * Avi Kivity <avi@qumranet.com>
  13. * Yaniv Kamay <yaniv@qumranet.com>
  14. * Amit Shah <amit.shah@qumranet.com>
  15. * Ben-Ami Yassour <benami@il.ibm.com>
  16. *
  17. * This work is licensed under the terms of the GNU GPL, version 2. See
  18. * the COPYING file in the top-level directory.
  19. *
  20. */
  21. #include <linux/kvm_host.h>
  22. #include "irq.h"
  23. #include "mmu.h"
  24. #include "i8254.h"
  25. #include "tss.h"
  26. #include "kvm_cache_regs.h"
  27. #include "x86.h"
  28. #include "cpuid.h"
  29. #include "pmu.h"
  30. #include "hyperv.h"
  31. #include <linux/clocksource.h>
  32. #include <linux/interrupt.h>
  33. #include <linux/kvm.h>
  34. #include <linux/fs.h>
  35. #include <linux/vmalloc.h>
  36. #include <linux/export.h>
  37. #include <linux/moduleparam.h>
  38. #include <linux/mman.h>
  39. #include <linux/highmem.h>
  40. #include <linux/iommu.h>
  41. #include <linux/intel-iommu.h>
  42. #include <linux/cpufreq.h>
  43. #include <linux/user-return-notifier.h>
  44. #include <linux/srcu.h>
  45. #include <linux/slab.h>
  46. #include <linux/perf_event.h>
  47. #include <linux/uaccess.h>
  48. #include <linux/hash.h>
  49. #include <linux/pci.h>
  50. #include <linux/timekeeper_internal.h>
  51. #include <linux/pvclock_gtod.h>
  52. #include <linux/kvm_irqfd.h>
  53. #include <linux/irqbypass.h>
  54. #include <linux/sched/stat.h>
  55. #include <linux/mem_encrypt.h>
  56. #include <trace/events/kvm.h>
  57. #include <asm/debugreg.h>
  58. #include <asm/msr.h>
  59. #include <asm/desc.h>
  60. #include <asm/mce.h>
  61. #include <linux/kernel_stat.h>
  62. #include <asm/fpu/internal.h> /* Ugh! */
  63. #include <asm/pvclock.h>
  64. #include <asm/div64.h>
  65. #include <asm/irq_remapping.h>
  66. #include <asm/mshyperv.h>
  67. #include <asm/hypervisor.h>
  68. #define CREATE_TRACE_POINTS
  69. #include "trace.h"
  70. #define MAX_IO_MSRS 256
  71. #define KVM_MAX_MCE_BANKS 32
  72. u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
  73. EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
  74. #define emul_to_vcpu(ctxt) \
  75. container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
  76. /* EFER defaults:
  77. * - enable syscall per default because its emulated by KVM
  78. * - enable LME and LMA per default on 64 bit KVM
  79. */
  80. #ifdef CONFIG_X86_64
  81. static
  82. u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
  83. #else
  84. static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  85. #endif
  86. #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
  87. #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
  88. #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
  89. KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  90. static void update_cr8_intercept(struct kvm_vcpu *vcpu);
  91. static void process_nmi(struct kvm_vcpu *vcpu);
  92. static void enter_smm(struct kvm_vcpu *vcpu);
  93. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
  94. static void store_regs(struct kvm_vcpu *vcpu);
  95. static int sync_regs(struct kvm_vcpu *vcpu);
  96. struct kvm_x86_ops *kvm_x86_ops __read_mostly;
  97. EXPORT_SYMBOL_GPL(kvm_x86_ops);
  98. static bool __read_mostly ignore_msrs = 0;
  99. module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
  100. static bool __read_mostly report_ignored_msrs = true;
  101. module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
  102. unsigned int min_timer_period_us = 200;
  103. module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
  104. static bool __read_mostly kvmclock_periodic_sync = true;
  105. module_param(kvmclock_periodic_sync, bool, S_IRUGO);
  106. bool __read_mostly kvm_has_tsc_control;
  107. EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
  108. u32 __read_mostly kvm_max_guest_tsc_khz;
  109. EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
  110. u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
  111. EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
  112. u64 __read_mostly kvm_max_tsc_scaling_ratio;
  113. EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
  114. u64 __read_mostly kvm_default_tsc_scaling_ratio;
  115. EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
  116. /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
  117. static u32 __read_mostly tsc_tolerance_ppm = 250;
  118. module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
  119. /* lapic timer advance (tscdeadline mode only) in nanoseconds */
  120. unsigned int __read_mostly lapic_timer_advance_ns = 0;
  121. module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
  122. EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
  123. static bool __read_mostly vector_hashing = true;
  124. module_param(vector_hashing, bool, S_IRUGO);
  125. bool __read_mostly enable_vmware_backdoor = false;
  126. module_param(enable_vmware_backdoor, bool, S_IRUGO);
  127. EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
  128. static bool __read_mostly force_emulation_prefix = false;
  129. module_param(force_emulation_prefix, bool, S_IRUGO);
  130. #define KVM_NR_SHARED_MSRS 16
  131. struct kvm_shared_msrs_global {
  132. int nr;
  133. u32 msrs[KVM_NR_SHARED_MSRS];
  134. };
  135. struct kvm_shared_msrs {
  136. struct user_return_notifier urn;
  137. bool registered;
  138. struct kvm_shared_msr_values {
  139. u64 host;
  140. u64 curr;
  141. } values[KVM_NR_SHARED_MSRS];
  142. };
  143. static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
  144. static struct kvm_shared_msrs __percpu *shared_msrs;
  145. struct kvm_stats_debugfs_item debugfs_entries[] = {
  146. { "pf_fixed", VCPU_STAT(pf_fixed) },
  147. { "pf_guest", VCPU_STAT(pf_guest) },
  148. { "tlb_flush", VCPU_STAT(tlb_flush) },
  149. { "invlpg", VCPU_STAT(invlpg) },
  150. { "exits", VCPU_STAT(exits) },
  151. { "io_exits", VCPU_STAT(io_exits) },
  152. { "mmio_exits", VCPU_STAT(mmio_exits) },
  153. { "signal_exits", VCPU_STAT(signal_exits) },
  154. { "irq_window", VCPU_STAT(irq_window_exits) },
  155. { "nmi_window", VCPU_STAT(nmi_window_exits) },
  156. { "halt_exits", VCPU_STAT(halt_exits) },
  157. { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
  158. { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
  159. { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
  160. { "halt_wakeup", VCPU_STAT(halt_wakeup) },
  161. { "hypercalls", VCPU_STAT(hypercalls) },
  162. { "request_irq", VCPU_STAT(request_irq_exits) },
  163. { "irq_exits", VCPU_STAT(irq_exits) },
  164. { "host_state_reload", VCPU_STAT(host_state_reload) },
  165. { "fpu_reload", VCPU_STAT(fpu_reload) },
  166. { "insn_emulation", VCPU_STAT(insn_emulation) },
  167. { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
  168. { "irq_injections", VCPU_STAT(irq_injections) },
  169. { "nmi_injections", VCPU_STAT(nmi_injections) },
  170. { "req_event", VCPU_STAT(req_event) },
  171. { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
  172. { "mmu_pte_write", VM_STAT(mmu_pte_write) },
  173. { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
  174. { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
  175. { "mmu_flooded", VM_STAT(mmu_flooded) },
  176. { "mmu_recycled", VM_STAT(mmu_recycled) },
  177. { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
  178. { "mmu_unsync", VM_STAT(mmu_unsync) },
  179. { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
  180. { "largepages", VM_STAT(lpages) },
  181. { "max_mmu_page_hash_collisions",
  182. VM_STAT(max_mmu_page_hash_collisions) },
  183. { NULL }
  184. };
  185. u64 __read_mostly host_xcr0;
  186. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
  187. static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  188. {
  189. int i;
  190. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
  191. vcpu->arch.apf.gfns[i] = ~0;
  192. }
  193. static void kvm_on_user_return(struct user_return_notifier *urn)
  194. {
  195. unsigned slot;
  196. struct kvm_shared_msrs *locals
  197. = container_of(urn, struct kvm_shared_msrs, urn);
  198. struct kvm_shared_msr_values *values;
  199. unsigned long flags;
  200. /*
  201. * Disabling irqs at this point since the following code could be
  202. * interrupted and executed through kvm_arch_hardware_disable()
  203. */
  204. local_irq_save(flags);
  205. if (locals->registered) {
  206. locals->registered = false;
  207. user_return_notifier_unregister(urn);
  208. }
  209. local_irq_restore(flags);
  210. for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
  211. values = &locals->values[slot];
  212. if (values->host != values->curr) {
  213. wrmsrl(shared_msrs_global.msrs[slot], values->host);
  214. values->curr = values->host;
  215. }
  216. }
  217. }
  218. static void shared_msr_update(unsigned slot, u32 msr)
  219. {
  220. u64 value;
  221. unsigned int cpu = smp_processor_id();
  222. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  223. /* only read, and nobody should modify it at this time,
  224. * so don't need lock */
  225. if (slot >= shared_msrs_global.nr) {
  226. printk(KERN_ERR "kvm: invalid MSR slot!");
  227. return;
  228. }
  229. rdmsrl_safe(msr, &value);
  230. smsr->values[slot].host = value;
  231. smsr->values[slot].curr = value;
  232. }
  233. void kvm_define_shared_msr(unsigned slot, u32 msr)
  234. {
  235. BUG_ON(slot >= KVM_NR_SHARED_MSRS);
  236. shared_msrs_global.msrs[slot] = msr;
  237. if (slot >= shared_msrs_global.nr)
  238. shared_msrs_global.nr = slot + 1;
  239. }
  240. EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
  241. static void kvm_shared_msr_cpu_online(void)
  242. {
  243. unsigned i;
  244. for (i = 0; i < shared_msrs_global.nr; ++i)
  245. shared_msr_update(i, shared_msrs_global.msrs[i]);
  246. }
  247. int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
  248. {
  249. unsigned int cpu = smp_processor_id();
  250. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  251. int err;
  252. if (((value ^ smsr->values[slot].curr) & mask) == 0)
  253. return 0;
  254. smsr->values[slot].curr = value;
  255. err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
  256. if (err)
  257. return 1;
  258. if (!smsr->registered) {
  259. smsr->urn.on_user_return = kvm_on_user_return;
  260. user_return_notifier_register(&smsr->urn);
  261. smsr->registered = true;
  262. }
  263. return 0;
  264. }
  265. EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
  266. static void drop_user_return_notifiers(void)
  267. {
  268. unsigned int cpu = smp_processor_id();
  269. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  270. if (smsr->registered)
  271. kvm_on_user_return(&smsr->urn);
  272. }
  273. u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  274. {
  275. return vcpu->arch.apic_base;
  276. }
  277. EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  278. enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
  279. {
  280. return kvm_apic_mode(kvm_get_apic_base(vcpu));
  281. }
  282. EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
  283. int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  284. {
  285. enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
  286. enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
  287. u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
  288. (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
  289. if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
  290. return 1;
  291. if (!msr_info->host_initiated) {
  292. if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
  293. return 1;
  294. if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
  295. return 1;
  296. }
  297. kvm_lapic_set_base(vcpu, msr_info->data);
  298. return 0;
  299. }
  300. EXPORT_SYMBOL_GPL(kvm_set_apic_base);
  301. asmlinkage __visible void kvm_spurious_fault(void)
  302. {
  303. /* Fault while not rebooting. We want the trace. */
  304. BUG();
  305. }
  306. EXPORT_SYMBOL_GPL(kvm_spurious_fault);
  307. #define EXCPT_BENIGN 0
  308. #define EXCPT_CONTRIBUTORY 1
  309. #define EXCPT_PF 2
  310. static int exception_class(int vector)
  311. {
  312. switch (vector) {
  313. case PF_VECTOR:
  314. return EXCPT_PF;
  315. case DE_VECTOR:
  316. case TS_VECTOR:
  317. case NP_VECTOR:
  318. case SS_VECTOR:
  319. case GP_VECTOR:
  320. return EXCPT_CONTRIBUTORY;
  321. default:
  322. break;
  323. }
  324. return EXCPT_BENIGN;
  325. }
  326. #define EXCPT_FAULT 0
  327. #define EXCPT_TRAP 1
  328. #define EXCPT_ABORT 2
  329. #define EXCPT_INTERRUPT 3
  330. static int exception_type(int vector)
  331. {
  332. unsigned int mask;
  333. if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
  334. return EXCPT_INTERRUPT;
  335. mask = 1 << vector;
  336. /* #DB is trap, as instruction watchpoints are handled elsewhere */
  337. if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
  338. return EXCPT_TRAP;
  339. if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
  340. return EXCPT_ABORT;
  341. /* Reserved exceptions will result in fault */
  342. return EXCPT_FAULT;
  343. }
  344. static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
  345. unsigned nr, bool has_error, u32 error_code,
  346. bool reinject)
  347. {
  348. u32 prev_nr;
  349. int class1, class2;
  350. kvm_make_request(KVM_REQ_EVENT, vcpu);
  351. if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
  352. queue:
  353. if (has_error && !is_protmode(vcpu))
  354. has_error = false;
  355. if (reinject) {
  356. /*
  357. * On vmentry, vcpu->arch.exception.pending is only
  358. * true if an event injection was blocked by
  359. * nested_run_pending. In that case, however,
  360. * vcpu_enter_guest requests an immediate exit,
  361. * and the guest shouldn't proceed far enough to
  362. * need reinjection.
  363. */
  364. WARN_ON_ONCE(vcpu->arch.exception.pending);
  365. vcpu->arch.exception.injected = true;
  366. } else {
  367. vcpu->arch.exception.pending = true;
  368. vcpu->arch.exception.injected = false;
  369. }
  370. vcpu->arch.exception.has_error_code = has_error;
  371. vcpu->arch.exception.nr = nr;
  372. vcpu->arch.exception.error_code = error_code;
  373. return;
  374. }
  375. /* to check exception */
  376. prev_nr = vcpu->arch.exception.nr;
  377. if (prev_nr == DF_VECTOR) {
  378. /* triple fault -> shutdown */
  379. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  380. return;
  381. }
  382. class1 = exception_class(prev_nr);
  383. class2 = exception_class(nr);
  384. if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
  385. || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  386. /*
  387. * Generate double fault per SDM Table 5-5. Set
  388. * exception.pending = true so that the double fault
  389. * can trigger a nested vmexit.
  390. */
  391. vcpu->arch.exception.pending = true;
  392. vcpu->arch.exception.injected = false;
  393. vcpu->arch.exception.has_error_code = true;
  394. vcpu->arch.exception.nr = DF_VECTOR;
  395. vcpu->arch.exception.error_code = 0;
  396. } else
  397. /* replace previous exception with a new one in a hope
  398. that instruction re-execution will regenerate lost
  399. exception */
  400. goto queue;
  401. }
  402. void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  403. {
  404. kvm_multiple_exception(vcpu, nr, false, 0, false);
  405. }
  406. EXPORT_SYMBOL_GPL(kvm_queue_exception);
  407. void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  408. {
  409. kvm_multiple_exception(vcpu, nr, false, 0, true);
  410. }
  411. EXPORT_SYMBOL_GPL(kvm_requeue_exception);
  412. int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
  413. {
  414. if (err)
  415. kvm_inject_gp(vcpu, 0);
  416. else
  417. return kvm_skip_emulated_instruction(vcpu);
  418. return 1;
  419. }
  420. EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
  421. void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  422. {
  423. ++vcpu->stat.pf_guest;
  424. vcpu->arch.exception.nested_apf =
  425. is_guest_mode(vcpu) && fault->async_page_fault;
  426. if (vcpu->arch.exception.nested_apf)
  427. vcpu->arch.apf.nested_apf_token = fault->address;
  428. else
  429. vcpu->arch.cr2 = fault->address;
  430. kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
  431. }
  432. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  433. static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  434. {
  435. if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  436. vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
  437. else
  438. vcpu->arch.mmu.inject_page_fault(vcpu, fault);
  439. return fault->nested_page_fault;
  440. }
  441. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  442. {
  443. atomic_inc(&vcpu->arch.nmi_queued);
  444. kvm_make_request(KVM_REQ_NMI, vcpu);
  445. }
  446. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  447. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  448. {
  449. kvm_multiple_exception(vcpu, nr, true, error_code, false);
  450. }
  451. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  452. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  453. {
  454. kvm_multiple_exception(vcpu, nr, true, error_code, true);
  455. }
  456. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  457. /*
  458. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  459. * a #GP and return false.
  460. */
  461. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  462. {
  463. if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  464. return true;
  465. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  466. return false;
  467. }
  468. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  469. bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
  470. {
  471. if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  472. return true;
  473. kvm_queue_exception(vcpu, UD_VECTOR);
  474. return false;
  475. }
  476. EXPORT_SYMBOL_GPL(kvm_require_dr);
  477. /*
  478. * This function will be used to read from the physical memory of the currently
  479. * running guest. The difference to kvm_vcpu_read_guest_page is that this function
  480. * can read from guest physical or from the guest's guest physical memory.
  481. */
  482. int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  483. gfn_t ngfn, void *data, int offset, int len,
  484. u32 access)
  485. {
  486. struct x86_exception exception;
  487. gfn_t real_gfn;
  488. gpa_t ngpa;
  489. ngpa = gfn_to_gpa(ngfn);
  490. real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
  491. if (real_gfn == UNMAPPED_GVA)
  492. return -EFAULT;
  493. real_gfn = gpa_to_gfn(real_gfn);
  494. return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
  495. }
  496. EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
  497. static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  498. void *data, int offset, int len, u32 access)
  499. {
  500. return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  501. data, offset, len, access);
  502. }
  503. /*
  504. * Load the pae pdptrs. Return true is they are all valid.
  505. */
  506. int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
  507. {
  508. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  509. unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  510. int i;
  511. int ret;
  512. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  513. ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  514. offset * sizeof(u64), sizeof(pdpte),
  515. PFERR_USER_MASK|PFERR_WRITE_MASK);
  516. if (ret < 0) {
  517. ret = 0;
  518. goto out;
  519. }
  520. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  521. if ((pdpte[i] & PT_PRESENT_MASK) &&
  522. (pdpte[i] &
  523. vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
  524. ret = 0;
  525. goto out;
  526. }
  527. }
  528. ret = 1;
  529. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  530. __set_bit(VCPU_EXREG_PDPTR,
  531. (unsigned long *)&vcpu->arch.regs_avail);
  532. __set_bit(VCPU_EXREG_PDPTR,
  533. (unsigned long *)&vcpu->arch.regs_dirty);
  534. out:
  535. return ret;
  536. }
  537. EXPORT_SYMBOL_GPL(load_pdptrs);
  538. bool pdptrs_changed(struct kvm_vcpu *vcpu)
  539. {
  540. u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
  541. bool changed = true;
  542. int offset;
  543. gfn_t gfn;
  544. int r;
  545. if (is_long_mode(vcpu) || !is_pae(vcpu))
  546. return false;
  547. if (!test_bit(VCPU_EXREG_PDPTR,
  548. (unsigned long *)&vcpu->arch.regs_avail))
  549. return true;
  550. gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
  551. offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
  552. r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  553. PFERR_USER_MASK | PFERR_WRITE_MASK);
  554. if (r < 0)
  555. goto out;
  556. changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
  557. out:
  558. return changed;
  559. }
  560. EXPORT_SYMBOL_GPL(pdptrs_changed);
  561. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  562. {
  563. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  564. unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
  565. cr0 |= X86_CR0_ET;
  566. #ifdef CONFIG_X86_64
  567. if (cr0 & 0xffffffff00000000UL)
  568. return 1;
  569. #endif
  570. cr0 &= ~CR0_RESERVED_BITS;
  571. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  572. return 1;
  573. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  574. return 1;
  575. if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  576. #ifdef CONFIG_X86_64
  577. if ((vcpu->arch.efer & EFER_LME)) {
  578. int cs_db, cs_l;
  579. if (!is_pae(vcpu))
  580. return 1;
  581. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  582. if (cs_l)
  583. return 1;
  584. } else
  585. #endif
  586. if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  587. kvm_read_cr3(vcpu)))
  588. return 1;
  589. }
  590. if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  591. return 1;
  592. kvm_x86_ops->set_cr0(vcpu, cr0);
  593. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  594. kvm_clear_async_pf_completion_queue(vcpu);
  595. kvm_async_pf_hash_reset(vcpu);
  596. }
  597. if ((cr0 ^ old_cr0) & update_bits)
  598. kvm_mmu_reset_context(vcpu);
  599. if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
  600. kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
  601. !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
  602. kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
  603. return 0;
  604. }
  605. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  606. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  607. {
  608. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  609. }
  610. EXPORT_SYMBOL_GPL(kvm_lmsw);
  611. static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  612. {
  613. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  614. !vcpu->guest_xcr0_loaded) {
  615. /* kvm_set_xcr() also depends on this */
  616. if (vcpu->arch.xcr0 != host_xcr0)
  617. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  618. vcpu->guest_xcr0_loaded = 1;
  619. }
  620. }
  621. static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  622. {
  623. if (vcpu->guest_xcr0_loaded) {
  624. if (vcpu->arch.xcr0 != host_xcr0)
  625. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  626. vcpu->guest_xcr0_loaded = 0;
  627. }
  628. }
  629. static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  630. {
  631. u64 xcr0 = xcr;
  632. u64 old_xcr0 = vcpu->arch.xcr0;
  633. u64 valid_bits;
  634. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  635. if (index != XCR_XFEATURE_ENABLED_MASK)
  636. return 1;
  637. if (!(xcr0 & XFEATURE_MASK_FP))
  638. return 1;
  639. if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
  640. return 1;
  641. /*
  642. * Do not allow the guest to set bits that we do not support
  643. * saving. However, xcr0 bit 0 is always set, even if the
  644. * emulated CPU does not support XSAVE (see fx_init).
  645. */
  646. valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
  647. if (xcr0 & ~valid_bits)
  648. return 1;
  649. if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
  650. (!(xcr0 & XFEATURE_MASK_BNDCSR)))
  651. return 1;
  652. if (xcr0 & XFEATURE_MASK_AVX512) {
  653. if (!(xcr0 & XFEATURE_MASK_YMM))
  654. return 1;
  655. if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
  656. return 1;
  657. }
  658. vcpu->arch.xcr0 = xcr0;
  659. if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
  660. kvm_update_cpuid(vcpu);
  661. return 0;
  662. }
  663. int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  664. {
  665. if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
  666. __kvm_set_xcr(vcpu, index, xcr)) {
  667. kvm_inject_gp(vcpu, 0);
  668. return 1;
  669. }
  670. return 0;
  671. }
  672. EXPORT_SYMBOL_GPL(kvm_set_xcr);
  673. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  674. {
  675. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  676. unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
  677. X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
  678. if (cr4 & CR4_RESERVED_BITS)
  679. return 1;
  680. if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
  681. return 1;
  682. if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
  683. return 1;
  684. if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
  685. return 1;
  686. if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
  687. return 1;
  688. if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
  689. return 1;
  690. if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
  691. return 1;
  692. if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
  693. return 1;
  694. if (is_long_mode(vcpu)) {
  695. if (!(cr4 & X86_CR4_PAE))
  696. return 1;
  697. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  698. && ((cr4 ^ old_cr4) & pdptr_bits)
  699. && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  700. kvm_read_cr3(vcpu)))
  701. return 1;
  702. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  703. if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
  704. return 1;
  705. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  706. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  707. return 1;
  708. }
  709. if (kvm_x86_ops->set_cr4(vcpu, cr4))
  710. return 1;
  711. if (((cr4 ^ old_cr4) & pdptr_bits) ||
  712. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  713. kvm_mmu_reset_context(vcpu);
  714. if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  715. kvm_update_cpuid(vcpu);
  716. return 0;
  717. }
  718. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  719. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  720. {
  721. bool skip_tlb_flush = false;
  722. #ifdef CONFIG_X86_64
  723. bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
  724. if (pcid_enabled) {
  725. skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
  726. cr3 &= ~X86_CR3_PCID_NOFLUSH;
  727. }
  728. #endif
  729. if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
  730. if (!skip_tlb_flush) {
  731. kvm_mmu_sync_roots(vcpu);
  732. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  733. }
  734. return 0;
  735. }
  736. if (is_long_mode(vcpu) &&
  737. (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
  738. return 1;
  739. else if (is_pae(vcpu) && is_paging(vcpu) &&
  740. !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
  741. return 1;
  742. kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
  743. vcpu->arch.cr3 = cr3;
  744. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  745. return 0;
  746. }
  747. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  748. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  749. {
  750. if (cr8 & CR8_RESERVED_BITS)
  751. return 1;
  752. if (lapic_in_kernel(vcpu))
  753. kvm_lapic_set_tpr(vcpu, cr8);
  754. else
  755. vcpu->arch.cr8 = cr8;
  756. return 0;
  757. }
  758. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  759. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  760. {
  761. if (lapic_in_kernel(vcpu))
  762. return kvm_lapic_get_cr8(vcpu);
  763. else
  764. return vcpu->arch.cr8;
  765. }
  766. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  767. static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
  768. {
  769. int i;
  770. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
  771. for (i = 0; i < KVM_NR_DB_REGS; i++)
  772. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  773. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
  774. }
  775. }
  776. static void kvm_update_dr6(struct kvm_vcpu *vcpu)
  777. {
  778. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  779. kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
  780. }
  781. static void kvm_update_dr7(struct kvm_vcpu *vcpu)
  782. {
  783. unsigned long dr7;
  784. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  785. dr7 = vcpu->arch.guest_debug_dr7;
  786. else
  787. dr7 = vcpu->arch.dr7;
  788. kvm_x86_ops->set_dr7(vcpu, dr7);
  789. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
  790. if (dr7 & DR7_BP_EN_MASK)
  791. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
  792. }
  793. static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
  794. {
  795. u64 fixed = DR6_FIXED_1;
  796. if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
  797. fixed |= DR6_RTM;
  798. return fixed;
  799. }
  800. static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  801. {
  802. switch (dr) {
  803. case 0 ... 3:
  804. vcpu->arch.db[dr] = val;
  805. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  806. vcpu->arch.eff_db[dr] = val;
  807. break;
  808. case 4:
  809. /* fall through */
  810. case 6:
  811. if (val & 0xffffffff00000000ULL)
  812. return -1; /* #GP */
  813. vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
  814. kvm_update_dr6(vcpu);
  815. break;
  816. case 5:
  817. /* fall through */
  818. default: /* 7 */
  819. if (val & 0xffffffff00000000ULL)
  820. return -1; /* #GP */
  821. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  822. kvm_update_dr7(vcpu);
  823. break;
  824. }
  825. return 0;
  826. }
  827. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  828. {
  829. if (__kvm_set_dr(vcpu, dr, val)) {
  830. kvm_inject_gp(vcpu, 0);
  831. return 1;
  832. }
  833. return 0;
  834. }
  835. EXPORT_SYMBOL_GPL(kvm_set_dr);
  836. int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  837. {
  838. switch (dr) {
  839. case 0 ... 3:
  840. *val = vcpu->arch.db[dr];
  841. break;
  842. case 4:
  843. /* fall through */
  844. case 6:
  845. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  846. *val = vcpu->arch.dr6;
  847. else
  848. *val = kvm_x86_ops->get_dr6(vcpu);
  849. break;
  850. case 5:
  851. /* fall through */
  852. default: /* 7 */
  853. *val = vcpu->arch.dr7;
  854. break;
  855. }
  856. return 0;
  857. }
  858. EXPORT_SYMBOL_GPL(kvm_get_dr);
  859. bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  860. {
  861. u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  862. u64 data;
  863. int err;
  864. err = kvm_pmu_rdpmc(vcpu, ecx, &data);
  865. if (err)
  866. return err;
  867. kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  868. kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  869. return err;
  870. }
  871. EXPORT_SYMBOL_GPL(kvm_rdpmc);
  872. /*
  873. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  874. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  875. *
  876. * This list is modified at module load time to reflect the
  877. * capabilities of the host cpu. This capabilities test skips MSRs that are
  878. * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
  879. * may depend on host virtualization features rather than host cpu features.
  880. */
  881. static u32 msrs_to_save[] = {
  882. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  883. MSR_STAR,
  884. #ifdef CONFIG_X86_64
  885. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  886. #endif
  887. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
  888. MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
  889. MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
  890. };
  891. static unsigned num_msrs_to_save;
  892. static u32 emulated_msrs[] = {
  893. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  894. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  895. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  896. HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
  897. HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
  898. HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
  899. HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
  900. HV_X64_MSR_RESET,
  901. HV_X64_MSR_VP_INDEX,
  902. HV_X64_MSR_VP_RUNTIME,
  903. HV_X64_MSR_SCONTROL,
  904. HV_X64_MSR_STIMER0_CONFIG,
  905. HV_X64_MSR_VP_ASSIST_PAGE,
  906. HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
  907. HV_X64_MSR_TSC_EMULATION_STATUS,
  908. MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  909. MSR_KVM_PV_EOI_EN,
  910. MSR_IA32_TSC_ADJUST,
  911. MSR_IA32_TSCDEADLINE,
  912. MSR_IA32_MISC_ENABLE,
  913. MSR_IA32_MCG_STATUS,
  914. MSR_IA32_MCG_CTL,
  915. MSR_IA32_MCG_EXT_CTL,
  916. MSR_IA32_SMBASE,
  917. MSR_SMI_COUNT,
  918. MSR_PLATFORM_INFO,
  919. MSR_MISC_FEATURES_ENABLES,
  920. MSR_AMD64_VIRT_SPEC_CTRL,
  921. };
  922. static unsigned num_emulated_msrs;
  923. /*
  924. * List of msr numbers which are used to expose MSR-based features that
  925. * can be used by a hypervisor to validate requested CPU features.
  926. */
  927. static u32 msr_based_features[] = {
  928. MSR_IA32_VMX_BASIC,
  929. MSR_IA32_VMX_TRUE_PINBASED_CTLS,
  930. MSR_IA32_VMX_PINBASED_CTLS,
  931. MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
  932. MSR_IA32_VMX_PROCBASED_CTLS,
  933. MSR_IA32_VMX_TRUE_EXIT_CTLS,
  934. MSR_IA32_VMX_EXIT_CTLS,
  935. MSR_IA32_VMX_TRUE_ENTRY_CTLS,
  936. MSR_IA32_VMX_ENTRY_CTLS,
  937. MSR_IA32_VMX_MISC,
  938. MSR_IA32_VMX_CR0_FIXED0,
  939. MSR_IA32_VMX_CR0_FIXED1,
  940. MSR_IA32_VMX_CR4_FIXED0,
  941. MSR_IA32_VMX_CR4_FIXED1,
  942. MSR_IA32_VMX_VMCS_ENUM,
  943. MSR_IA32_VMX_PROCBASED_CTLS2,
  944. MSR_IA32_VMX_EPT_VPID_CAP,
  945. MSR_IA32_VMX_VMFUNC,
  946. MSR_F10H_DECFG,
  947. MSR_IA32_UCODE_REV,
  948. MSR_IA32_ARCH_CAPABILITIES,
  949. };
  950. static unsigned int num_msr_based_features;
  951. static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
  952. {
  953. switch (msr->index) {
  954. case MSR_IA32_UCODE_REV:
  955. case MSR_IA32_ARCH_CAPABILITIES:
  956. rdmsrl_safe(msr->index, &msr->data);
  957. break;
  958. default:
  959. if (kvm_x86_ops->get_msr_feature(msr))
  960. return 1;
  961. }
  962. return 0;
  963. }
  964. static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  965. {
  966. struct kvm_msr_entry msr;
  967. int r;
  968. msr.index = index;
  969. r = kvm_get_msr_feature(&msr);
  970. if (r)
  971. return r;
  972. *data = msr.data;
  973. return 0;
  974. }
  975. bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  976. {
  977. if (efer & efer_reserved_bits)
  978. return false;
  979. if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
  980. return false;
  981. if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
  982. return false;
  983. return true;
  984. }
  985. EXPORT_SYMBOL_GPL(kvm_valid_efer);
  986. static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
  987. {
  988. u64 old_efer = vcpu->arch.efer;
  989. if (!kvm_valid_efer(vcpu, efer))
  990. return 1;
  991. if (is_paging(vcpu)
  992. && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  993. return 1;
  994. efer &= ~EFER_LMA;
  995. efer |= vcpu->arch.efer & EFER_LMA;
  996. kvm_x86_ops->set_efer(vcpu, efer);
  997. /* Update reserved bits */
  998. if ((efer ^ old_efer) & EFER_NX)
  999. kvm_mmu_reset_context(vcpu);
  1000. return 0;
  1001. }
  1002. void kvm_enable_efer_bits(u64 mask)
  1003. {
  1004. efer_reserved_bits &= ~mask;
  1005. }
  1006. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  1007. /*
  1008. * Writes msr value into into the appropriate "register".
  1009. * Returns 0 on success, non-0 otherwise.
  1010. * Assumes vcpu_load() was already called.
  1011. */
  1012. int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1013. {
  1014. switch (msr->index) {
  1015. case MSR_FS_BASE:
  1016. case MSR_GS_BASE:
  1017. case MSR_KERNEL_GS_BASE:
  1018. case MSR_CSTAR:
  1019. case MSR_LSTAR:
  1020. if (is_noncanonical_address(msr->data, vcpu))
  1021. return 1;
  1022. break;
  1023. case MSR_IA32_SYSENTER_EIP:
  1024. case MSR_IA32_SYSENTER_ESP:
  1025. /*
  1026. * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
  1027. * non-canonical address is written on Intel but not on
  1028. * AMD (which ignores the top 32-bits, because it does
  1029. * not implement 64-bit SYSENTER).
  1030. *
  1031. * 64-bit code should hence be able to write a non-canonical
  1032. * value on AMD. Making the address canonical ensures that
  1033. * vmentry does not fail on Intel after writing a non-canonical
  1034. * value, and that something deterministic happens if the guest
  1035. * invokes 64-bit SYSENTER.
  1036. */
  1037. msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
  1038. }
  1039. return kvm_x86_ops->set_msr(vcpu, msr);
  1040. }
  1041. EXPORT_SYMBOL_GPL(kvm_set_msr);
  1042. /*
  1043. * Adapt set_msr() to msr_io()'s calling convention
  1044. */
  1045. static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1046. {
  1047. struct msr_data msr;
  1048. int r;
  1049. msr.index = index;
  1050. msr.host_initiated = true;
  1051. r = kvm_get_msr(vcpu, &msr);
  1052. if (r)
  1053. return r;
  1054. *data = msr.data;
  1055. return 0;
  1056. }
  1057. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1058. {
  1059. struct msr_data msr;
  1060. msr.data = *data;
  1061. msr.index = index;
  1062. msr.host_initiated = true;
  1063. return kvm_set_msr(vcpu, &msr);
  1064. }
  1065. #ifdef CONFIG_X86_64
  1066. struct pvclock_gtod_data {
  1067. seqcount_t seq;
  1068. struct { /* extract of a clocksource struct */
  1069. int vclock_mode;
  1070. u64 cycle_last;
  1071. u64 mask;
  1072. u32 mult;
  1073. u32 shift;
  1074. } clock;
  1075. u64 boot_ns;
  1076. u64 nsec_base;
  1077. u64 wall_time_sec;
  1078. };
  1079. static struct pvclock_gtod_data pvclock_gtod_data;
  1080. static void update_pvclock_gtod(struct timekeeper *tk)
  1081. {
  1082. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  1083. u64 boot_ns;
  1084. boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
  1085. write_seqcount_begin(&vdata->seq);
  1086. /* copy pvclock gtod data */
  1087. vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
  1088. vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
  1089. vdata->clock.mask = tk->tkr_mono.mask;
  1090. vdata->clock.mult = tk->tkr_mono.mult;
  1091. vdata->clock.shift = tk->tkr_mono.shift;
  1092. vdata->boot_ns = boot_ns;
  1093. vdata->nsec_base = tk->tkr_mono.xtime_nsec;
  1094. vdata->wall_time_sec = tk->xtime_sec;
  1095. write_seqcount_end(&vdata->seq);
  1096. }
  1097. #endif
  1098. void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
  1099. {
  1100. /*
  1101. * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
  1102. * vcpu_enter_guest. This function is only called from
  1103. * the physical CPU that is running vcpu.
  1104. */
  1105. kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
  1106. }
  1107. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  1108. {
  1109. int version;
  1110. int r;
  1111. struct pvclock_wall_clock wc;
  1112. struct timespec64 boot;
  1113. if (!wall_clock)
  1114. return;
  1115. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  1116. if (r)
  1117. return;
  1118. if (version & 1)
  1119. ++version; /* first time write, random junk */
  1120. ++version;
  1121. if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
  1122. return;
  1123. /*
  1124. * The guest calculates current wall clock time by adding
  1125. * system time (updated by kvm_guest_time_update below) to the
  1126. * wall clock specified here. guest system time equals host
  1127. * system time for us, thus we must fill in host boot time here.
  1128. */
  1129. getboottime64(&boot);
  1130. if (kvm->arch.kvmclock_offset) {
  1131. struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
  1132. boot = timespec64_sub(boot, ts);
  1133. }
  1134. wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
  1135. wc.nsec = boot.tv_nsec;
  1136. wc.version = version;
  1137. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  1138. version++;
  1139. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  1140. }
  1141. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  1142. {
  1143. do_shl32_div32(dividend, divisor);
  1144. return dividend;
  1145. }
  1146. static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
  1147. s8 *pshift, u32 *pmultiplier)
  1148. {
  1149. uint64_t scaled64;
  1150. int32_t shift = 0;
  1151. uint64_t tps64;
  1152. uint32_t tps32;
  1153. tps64 = base_hz;
  1154. scaled64 = scaled_hz;
  1155. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  1156. tps64 >>= 1;
  1157. shift--;
  1158. }
  1159. tps32 = (uint32_t)tps64;
  1160. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  1161. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  1162. scaled64 >>= 1;
  1163. else
  1164. tps32 <<= 1;
  1165. shift++;
  1166. }
  1167. *pshift = shift;
  1168. *pmultiplier = div_frac(scaled64, tps32);
  1169. pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
  1170. __func__, base_hz, scaled_hz, shift, *pmultiplier);
  1171. }
  1172. #ifdef CONFIG_X86_64
  1173. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  1174. #endif
  1175. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  1176. static unsigned long max_tsc_khz;
  1177. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  1178. {
  1179. u64 v = (u64)khz * (1000000 + ppm);
  1180. do_div(v, 1000000);
  1181. return v;
  1182. }
  1183. static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
  1184. {
  1185. u64 ratio;
  1186. /* Guest TSC same frequency as host TSC? */
  1187. if (!scale) {
  1188. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1189. return 0;
  1190. }
  1191. /* TSC scaling supported? */
  1192. if (!kvm_has_tsc_control) {
  1193. if (user_tsc_khz > tsc_khz) {
  1194. vcpu->arch.tsc_catchup = 1;
  1195. vcpu->arch.tsc_always_catchup = 1;
  1196. return 0;
  1197. } else {
  1198. WARN(1, "user requested TSC rate below hardware speed\n");
  1199. return -1;
  1200. }
  1201. }
  1202. /* TSC scaling required - calculate ratio */
  1203. ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
  1204. user_tsc_khz, tsc_khz);
  1205. if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
  1206. WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
  1207. user_tsc_khz);
  1208. return -1;
  1209. }
  1210. vcpu->arch.tsc_scaling_ratio = ratio;
  1211. return 0;
  1212. }
  1213. static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
  1214. {
  1215. u32 thresh_lo, thresh_hi;
  1216. int use_scaling = 0;
  1217. /* tsc_khz can be zero if TSC calibration fails */
  1218. if (user_tsc_khz == 0) {
  1219. /* set tsc_scaling_ratio to a safe value */
  1220. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1221. return -1;
  1222. }
  1223. /* Compute a scale to convert nanoseconds in TSC cycles */
  1224. kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
  1225. &vcpu->arch.virtual_tsc_shift,
  1226. &vcpu->arch.virtual_tsc_mult);
  1227. vcpu->arch.virtual_tsc_khz = user_tsc_khz;
  1228. /*
  1229. * Compute the variation in TSC rate which is acceptable
  1230. * within the range of tolerance and decide if the
  1231. * rate being applied is within that bounds of the hardware
  1232. * rate. If so, no scaling or compensation need be done.
  1233. */
  1234. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  1235. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  1236. if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
  1237. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
  1238. use_scaling = 1;
  1239. }
  1240. return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
  1241. }
  1242. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  1243. {
  1244. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  1245. vcpu->arch.virtual_tsc_mult,
  1246. vcpu->arch.virtual_tsc_shift);
  1247. tsc += vcpu->arch.this_tsc_write;
  1248. return tsc;
  1249. }
  1250. static inline int gtod_is_based_on_tsc(int mode)
  1251. {
  1252. return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
  1253. }
  1254. static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
  1255. {
  1256. #ifdef CONFIG_X86_64
  1257. bool vcpus_matched;
  1258. struct kvm_arch *ka = &vcpu->kvm->arch;
  1259. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1260. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1261. atomic_read(&vcpu->kvm->online_vcpus));
  1262. /*
  1263. * Once the masterclock is enabled, always perform request in
  1264. * order to update it.
  1265. *
  1266. * In order to enable masterclock, the host clocksource must be TSC
  1267. * and the vcpus need to have matched TSCs. When that happens,
  1268. * perform request to enable masterclock.
  1269. */
  1270. if (ka->use_master_clock ||
  1271. (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
  1272. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  1273. trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
  1274. atomic_read(&vcpu->kvm->online_vcpus),
  1275. ka->use_master_clock, gtod->clock.vclock_mode);
  1276. #endif
  1277. }
  1278. static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
  1279. {
  1280. u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
  1281. vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
  1282. }
  1283. /*
  1284. * Multiply tsc by a fixed point number represented by ratio.
  1285. *
  1286. * The most significant 64-N bits (mult) of ratio represent the
  1287. * integral part of the fixed point number; the remaining N bits
  1288. * (frac) represent the fractional part, ie. ratio represents a fixed
  1289. * point number (mult + frac * 2^(-N)).
  1290. *
  1291. * N equals to kvm_tsc_scaling_ratio_frac_bits.
  1292. */
  1293. static inline u64 __scale_tsc(u64 ratio, u64 tsc)
  1294. {
  1295. return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
  1296. }
  1297. u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
  1298. {
  1299. u64 _tsc = tsc;
  1300. u64 ratio = vcpu->arch.tsc_scaling_ratio;
  1301. if (ratio != kvm_default_tsc_scaling_ratio)
  1302. _tsc = __scale_tsc(ratio, tsc);
  1303. return _tsc;
  1304. }
  1305. EXPORT_SYMBOL_GPL(kvm_scale_tsc);
  1306. static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
  1307. {
  1308. u64 tsc;
  1309. tsc = kvm_scale_tsc(vcpu, rdtsc());
  1310. return target_tsc - tsc;
  1311. }
  1312. u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
  1313. {
  1314. u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
  1315. return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
  1316. }
  1317. EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
  1318. static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
  1319. {
  1320. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  1321. vcpu->arch.tsc_offset = offset;
  1322. }
  1323. static inline bool kvm_check_tsc_unstable(void)
  1324. {
  1325. #ifdef CONFIG_X86_64
  1326. /*
  1327. * TSC is marked unstable when we're running on Hyper-V,
  1328. * 'TSC page' clocksource is good.
  1329. */
  1330. if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
  1331. return false;
  1332. #endif
  1333. return check_tsc_unstable();
  1334. }
  1335. void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1336. {
  1337. struct kvm *kvm = vcpu->kvm;
  1338. u64 offset, ns, elapsed;
  1339. unsigned long flags;
  1340. bool matched;
  1341. bool already_matched;
  1342. u64 data = msr->data;
  1343. bool synchronizing = false;
  1344. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  1345. offset = kvm_compute_tsc_offset(vcpu, data);
  1346. ns = ktime_get_boot_ns();
  1347. elapsed = ns - kvm->arch.last_tsc_nsec;
  1348. if (vcpu->arch.virtual_tsc_khz) {
  1349. if (data == 0 && msr->host_initiated) {
  1350. /*
  1351. * detection of vcpu initialization -- need to sync
  1352. * with other vCPUs. This particularly helps to keep
  1353. * kvm_clock stable after CPU hotplug
  1354. */
  1355. synchronizing = true;
  1356. } else {
  1357. u64 tsc_exp = kvm->arch.last_tsc_write +
  1358. nsec_to_cycles(vcpu, elapsed);
  1359. u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
  1360. /*
  1361. * Special case: TSC write with a small delta (1 second)
  1362. * of virtual cycle time against real time is
  1363. * interpreted as an attempt to synchronize the CPU.
  1364. */
  1365. synchronizing = data < tsc_exp + tsc_hz &&
  1366. data + tsc_hz > tsc_exp;
  1367. }
  1368. }
  1369. /*
  1370. * For a reliable TSC, we can match TSC offsets, and for an unstable
  1371. * TSC, we add elapsed time in this computation. We could let the
  1372. * compensation code attempt to catch up if we fall behind, but
  1373. * it's better to try to match offsets from the beginning.
  1374. */
  1375. if (synchronizing &&
  1376. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  1377. if (!kvm_check_tsc_unstable()) {
  1378. offset = kvm->arch.cur_tsc_offset;
  1379. pr_debug("kvm: matched tsc offset for %llu\n", data);
  1380. } else {
  1381. u64 delta = nsec_to_cycles(vcpu, elapsed);
  1382. data += delta;
  1383. offset = kvm_compute_tsc_offset(vcpu, data);
  1384. pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
  1385. }
  1386. matched = true;
  1387. already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
  1388. } else {
  1389. /*
  1390. * We split periods of matched TSC writes into generations.
  1391. * For each generation, we track the original measured
  1392. * nanosecond time, offset, and write, so if TSCs are in
  1393. * sync, we can match exact offset, and if not, we can match
  1394. * exact software computation in compute_guest_tsc()
  1395. *
  1396. * These values are tracked in kvm->arch.cur_xxx variables.
  1397. */
  1398. kvm->arch.cur_tsc_generation++;
  1399. kvm->arch.cur_tsc_nsec = ns;
  1400. kvm->arch.cur_tsc_write = data;
  1401. kvm->arch.cur_tsc_offset = offset;
  1402. matched = false;
  1403. pr_debug("kvm: new tsc generation %llu, clock %llu\n",
  1404. kvm->arch.cur_tsc_generation, data);
  1405. }
  1406. /*
  1407. * We also track th most recent recorded KHZ, write and time to
  1408. * allow the matching interval to be extended at each write.
  1409. */
  1410. kvm->arch.last_tsc_nsec = ns;
  1411. kvm->arch.last_tsc_write = data;
  1412. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  1413. vcpu->arch.last_guest_tsc = data;
  1414. /* Keep track of which generation this VCPU has synchronized to */
  1415. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  1416. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  1417. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  1418. if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
  1419. update_ia32_tsc_adjust_msr(vcpu, offset);
  1420. kvm_vcpu_write_tsc_offset(vcpu, offset);
  1421. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  1422. spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
  1423. if (!matched) {
  1424. kvm->arch.nr_vcpus_matched_tsc = 0;
  1425. } else if (!already_matched) {
  1426. kvm->arch.nr_vcpus_matched_tsc++;
  1427. }
  1428. kvm_track_tsc_matching(vcpu);
  1429. spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
  1430. }
  1431. EXPORT_SYMBOL_GPL(kvm_write_tsc);
  1432. static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
  1433. s64 adjustment)
  1434. {
  1435. kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
  1436. }
  1437. static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
  1438. {
  1439. if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
  1440. WARN_ON(adjustment < 0);
  1441. adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
  1442. adjust_tsc_offset_guest(vcpu, adjustment);
  1443. }
  1444. #ifdef CONFIG_X86_64
  1445. static u64 read_tsc(void)
  1446. {
  1447. u64 ret = (u64)rdtsc_ordered();
  1448. u64 last = pvclock_gtod_data.clock.cycle_last;
  1449. if (likely(ret >= last))
  1450. return ret;
  1451. /*
  1452. * GCC likes to generate cmov here, but this branch is extremely
  1453. * predictable (it's just a function of time and the likely is
  1454. * very likely) and there's a data dependence, so force GCC
  1455. * to generate a branch instead. I don't barrier() because
  1456. * we don't actually need a barrier, and if this function
  1457. * ever gets inlined it will generate worse code.
  1458. */
  1459. asm volatile ("");
  1460. return last;
  1461. }
  1462. static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
  1463. {
  1464. long v;
  1465. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1466. u64 tsc_pg_val;
  1467. switch (gtod->clock.vclock_mode) {
  1468. case VCLOCK_HVCLOCK:
  1469. tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
  1470. tsc_timestamp);
  1471. if (tsc_pg_val != U64_MAX) {
  1472. /* TSC page valid */
  1473. *mode = VCLOCK_HVCLOCK;
  1474. v = (tsc_pg_val - gtod->clock.cycle_last) &
  1475. gtod->clock.mask;
  1476. } else {
  1477. /* TSC page invalid */
  1478. *mode = VCLOCK_NONE;
  1479. }
  1480. break;
  1481. case VCLOCK_TSC:
  1482. *mode = VCLOCK_TSC;
  1483. *tsc_timestamp = read_tsc();
  1484. v = (*tsc_timestamp - gtod->clock.cycle_last) &
  1485. gtod->clock.mask;
  1486. break;
  1487. default:
  1488. *mode = VCLOCK_NONE;
  1489. }
  1490. if (*mode == VCLOCK_NONE)
  1491. *tsc_timestamp = v = 0;
  1492. return v * gtod->clock.mult;
  1493. }
  1494. static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
  1495. {
  1496. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1497. unsigned long seq;
  1498. int mode;
  1499. u64 ns;
  1500. do {
  1501. seq = read_seqcount_begin(&gtod->seq);
  1502. ns = gtod->nsec_base;
  1503. ns += vgettsc(tsc_timestamp, &mode);
  1504. ns >>= gtod->clock.shift;
  1505. ns += gtod->boot_ns;
  1506. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1507. *t = ns;
  1508. return mode;
  1509. }
  1510. static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
  1511. {
  1512. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1513. unsigned long seq;
  1514. int mode;
  1515. u64 ns;
  1516. do {
  1517. seq = read_seqcount_begin(&gtod->seq);
  1518. ts->tv_sec = gtod->wall_time_sec;
  1519. ns = gtod->nsec_base;
  1520. ns += vgettsc(tsc_timestamp, &mode);
  1521. ns >>= gtod->clock.shift;
  1522. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1523. ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
  1524. ts->tv_nsec = ns;
  1525. return mode;
  1526. }
  1527. /* returns true if host is using TSC based clocksource */
  1528. static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
  1529. {
  1530. /* checked again under seqlock below */
  1531. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  1532. return false;
  1533. return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
  1534. tsc_timestamp));
  1535. }
  1536. /* returns true if host is using TSC based clocksource */
  1537. static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
  1538. u64 *tsc_timestamp)
  1539. {
  1540. /* checked again under seqlock below */
  1541. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  1542. return false;
  1543. return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
  1544. }
  1545. #endif
  1546. /*
  1547. *
  1548. * Assuming a stable TSC across physical CPUS, and a stable TSC
  1549. * across virtual CPUs, the following condition is possible.
  1550. * Each numbered line represents an event visible to both
  1551. * CPUs at the next numbered event.
  1552. *
  1553. * "timespecX" represents host monotonic time. "tscX" represents
  1554. * RDTSC value.
  1555. *
  1556. * VCPU0 on CPU0 | VCPU1 on CPU1
  1557. *
  1558. * 1. read timespec0,tsc0
  1559. * 2. | timespec1 = timespec0 + N
  1560. * | tsc1 = tsc0 + M
  1561. * 3. transition to guest | transition to guest
  1562. * 4. ret0 = timespec0 + (rdtsc - tsc0) |
  1563. * 5. | ret1 = timespec1 + (rdtsc - tsc1)
  1564. * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
  1565. *
  1566. * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
  1567. *
  1568. * - ret0 < ret1
  1569. * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
  1570. * ...
  1571. * - 0 < N - M => M < N
  1572. *
  1573. * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
  1574. * always the case (the difference between two distinct xtime instances
  1575. * might be smaller then the difference between corresponding TSC reads,
  1576. * when updating guest vcpus pvclock areas).
  1577. *
  1578. * To avoid that problem, do not allow visibility of distinct
  1579. * system_timestamp/tsc_timestamp values simultaneously: use a master
  1580. * copy of host monotonic time values. Update that master copy
  1581. * in lockstep.
  1582. *
  1583. * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
  1584. *
  1585. */
  1586. static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
  1587. {
  1588. #ifdef CONFIG_X86_64
  1589. struct kvm_arch *ka = &kvm->arch;
  1590. int vclock_mode;
  1591. bool host_tsc_clocksource, vcpus_matched;
  1592. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1593. atomic_read(&kvm->online_vcpus));
  1594. /*
  1595. * If the host uses TSC clock, then passthrough TSC as stable
  1596. * to the guest.
  1597. */
  1598. host_tsc_clocksource = kvm_get_time_and_clockread(
  1599. &ka->master_kernel_ns,
  1600. &ka->master_cycle_now);
  1601. ka->use_master_clock = host_tsc_clocksource && vcpus_matched
  1602. && !ka->backwards_tsc_observed
  1603. && !ka->boot_vcpu_runs_old_kvmclock;
  1604. if (ka->use_master_clock)
  1605. atomic_set(&kvm_guest_has_master_clock, 1);
  1606. vclock_mode = pvclock_gtod_data.clock.vclock_mode;
  1607. trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
  1608. vcpus_matched);
  1609. #endif
  1610. }
  1611. void kvm_make_mclock_inprogress_request(struct kvm *kvm)
  1612. {
  1613. kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
  1614. }
  1615. static void kvm_gen_update_masterclock(struct kvm *kvm)
  1616. {
  1617. #ifdef CONFIG_X86_64
  1618. int i;
  1619. struct kvm_vcpu *vcpu;
  1620. struct kvm_arch *ka = &kvm->arch;
  1621. spin_lock(&ka->pvclock_gtod_sync_lock);
  1622. kvm_make_mclock_inprogress_request(kvm);
  1623. /* no guest entries from this point */
  1624. pvclock_update_vm_gtod_copy(kvm);
  1625. kvm_for_each_vcpu(i, vcpu, kvm)
  1626. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1627. /* guest entries allowed */
  1628. kvm_for_each_vcpu(i, vcpu, kvm)
  1629. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  1630. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1631. #endif
  1632. }
  1633. u64 get_kvmclock_ns(struct kvm *kvm)
  1634. {
  1635. struct kvm_arch *ka = &kvm->arch;
  1636. struct pvclock_vcpu_time_info hv_clock;
  1637. u64 ret;
  1638. spin_lock(&ka->pvclock_gtod_sync_lock);
  1639. if (!ka->use_master_clock) {
  1640. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1641. return ktime_get_boot_ns() + ka->kvmclock_offset;
  1642. }
  1643. hv_clock.tsc_timestamp = ka->master_cycle_now;
  1644. hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
  1645. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1646. /* both __this_cpu_read() and rdtsc() should be on the same cpu */
  1647. get_cpu();
  1648. if (__this_cpu_read(cpu_tsc_khz)) {
  1649. kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
  1650. &hv_clock.tsc_shift,
  1651. &hv_clock.tsc_to_system_mul);
  1652. ret = __pvclock_read_cycles(&hv_clock, rdtsc());
  1653. } else
  1654. ret = ktime_get_boot_ns() + ka->kvmclock_offset;
  1655. put_cpu();
  1656. return ret;
  1657. }
  1658. static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
  1659. {
  1660. struct kvm_vcpu_arch *vcpu = &v->arch;
  1661. struct pvclock_vcpu_time_info guest_hv_clock;
  1662. if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
  1663. &guest_hv_clock, sizeof(guest_hv_clock))))
  1664. return;
  1665. /* This VCPU is paused, but it's legal for a guest to read another
  1666. * VCPU's kvmclock, so we really have to follow the specification where
  1667. * it says that version is odd if data is being modified, and even after
  1668. * it is consistent.
  1669. *
  1670. * Version field updates must be kept separate. This is because
  1671. * kvm_write_guest_cached might use a "rep movs" instruction, and
  1672. * writes within a string instruction are weakly ordered. So there
  1673. * are three writes overall.
  1674. *
  1675. * As a small optimization, only write the version field in the first
  1676. * and third write. The vcpu->pv_time cache is still valid, because the
  1677. * version field is the first in the struct.
  1678. */
  1679. BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
  1680. if (guest_hv_clock.version & 1)
  1681. ++guest_hv_clock.version; /* first time write, random junk */
  1682. vcpu->hv_clock.version = guest_hv_clock.version + 1;
  1683. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1684. &vcpu->hv_clock,
  1685. sizeof(vcpu->hv_clock.version));
  1686. smp_wmb();
  1687. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  1688. vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
  1689. if (vcpu->pvclock_set_guest_stopped_request) {
  1690. vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
  1691. vcpu->pvclock_set_guest_stopped_request = false;
  1692. }
  1693. trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
  1694. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1695. &vcpu->hv_clock,
  1696. sizeof(vcpu->hv_clock));
  1697. smp_wmb();
  1698. vcpu->hv_clock.version++;
  1699. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1700. &vcpu->hv_clock,
  1701. sizeof(vcpu->hv_clock.version));
  1702. }
  1703. static int kvm_guest_time_update(struct kvm_vcpu *v)
  1704. {
  1705. unsigned long flags, tgt_tsc_khz;
  1706. struct kvm_vcpu_arch *vcpu = &v->arch;
  1707. struct kvm_arch *ka = &v->kvm->arch;
  1708. s64 kernel_ns;
  1709. u64 tsc_timestamp, host_tsc;
  1710. u8 pvclock_flags;
  1711. bool use_master_clock;
  1712. kernel_ns = 0;
  1713. host_tsc = 0;
  1714. /*
  1715. * If the host uses TSC clock, then passthrough TSC as stable
  1716. * to the guest.
  1717. */
  1718. spin_lock(&ka->pvclock_gtod_sync_lock);
  1719. use_master_clock = ka->use_master_clock;
  1720. if (use_master_clock) {
  1721. host_tsc = ka->master_cycle_now;
  1722. kernel_ns = ka->master_kernel_ns;
  1723. }
  1724. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1725. /* Keep irq disabled to prevent changes to the clock */
  1726. local_irq_save(flags);
  1727. tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
  1728. if (unlikely(tgt_tsc_khz == 0)) {
  1729. local_irq_restore(flags);
  1730. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1731. return 1;
  1732. }
  1733. if (!use_master_clock) {
  1734. host_tsc = rdtsc();
  1735. kernel_ns = ktime_get_boot_ns();
  1736. }
  1737. tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
  1738. /*
  1739. * We may have to catch up the TSC to match elapsed wall clock
  1740. * time for two reasons, even if kvmclock is used.
  1741. * 1) CPU could have been running below the maximum TSC rate
  1742. * 2) Broken TSC compensation resets the base at each VCPU
  1743. * entry to avoid unknown leaps of TSC even when running
  1744. * again on the same CPU. This may cause apparent elapsed
  1745. * time to disappear, and the guest to stand still or run
  1746. * very slowly.
  1747. */
  1748. if (vcpu->tsc_catchup) {
  1749. u64 tsc = compute_guest_tsc(v, kernel_ns);
  1750. if (tsc > tsc_timestamp) {
  1751. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  1752. tsc_timestamp = tsc;
  1753. }
  1754. }
  1755. local_irq_restore(flags);
  1756. /* With all the info we got, fill in the values */
  1757. if (kvm_has_tsc_control)
  1758. tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
  1759. if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
  1760. kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
  1761. &vcpu->hv_clock.tsc_shift,
  1762. &vcpu->hv_clock.tsc_to_system_mul);
  1763. vcpu->hw_tsc_khz = tgt_tsc_khz;
  1764. }
  1765. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  1766. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  1767. vcpu->last_guest_tsc = tsc_timestamp;
  1768. /* If the host uses TSC clocksource, then it is stable */
  1769. pvclock_flags = 0;
  1770. if (use_master_clock)
  1771. pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
  1772. vcpu->hv_clock.flags = pvclock_flags;
  1773. if (vcpu->pv_time_enabled)
  1774. kvm_setup_pvclock_page(v);
  1775. if (v == kvm_get_vcpu(v->kvm, 0))
  1776. kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
  1777. return 0;
  1778. }
  1779. /*
  1780. * kvmclock updates which are isolated to a given vcpu, such as
  1781. * vcpu->cpu migration, should not allow system_timestamp from
  1782. * the rest of the vcpus to remain static. Otherwise ntp frequency
  1783. * correction applies to one vcpu's system_timestamp but not
  1784. * the others.
  1785. *
  1786. * So in those cases, request a kvmclock update for all vcpus.
  1787. * We need to rate-limit these requests though, as they can
  1788. * considerably slow guests that have a large number of vcpus.
  1789. * The time for a remote vcpu to update its kvmclock is bound
  1790. * by the delay we use to rate-limit the updates.
  1791. */
  1792. #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
  1793. static void kvmclock_update_fn(struct work_struct *work)
  1794. {
  1795. int i;
  1796. struct delayed_work *dwork = to_delayed_work(work);
  1797. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1798. kvmclock_update_work);
  1799. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1800. struct kvm_vcpu *vcpu;
  1801. kvm_for_each_vcpu(i, vcpu, kvm) {
  1802. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1803. kvm_vcpu_kick(vcpu);
  1804. }
  1805. }
  1806. static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
  1807. {
  1808. struct kvm *kvm = v->kvm;
  1809. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1810. schedule_delayed_work(&kvm->arch.kvmclock_update_work,
  1811. KVMCLOCK_UPDATE_DELAY);
  1812. }
  1813. #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
  1814. static void kvmclock_sync_fn(struct work_struct *work)
  1815. {
  1816. struct delayed_work *dwork = to_delayed_work(work);
  1817. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1818. kvmclock_sync_work);
  1819. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1820. if (!kvmclock_periodic_sync)
  1821. return;
  1822. schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
  1823. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  1824. KVMCLOCK_SYNC_PERIOD);
  1825. }
  1826. static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1827. {
  1828. u64 mcg_cap = vcpu->arch.mcg_cap;
  1829. unsigned bank_num = mcg_cap & 0xff;
  1830. u32 msr = msr_info->index;
  1831. u64 data = msr_info->data;
  1832. switch (msr) {
  1833. case MSR_IA32_MCG_STATUS:
  1834. vcpu->arch.mcg_status = data;
  1835. break;
  1836. case MSR_IA32_MCG_CTL:
  1837. if (!(mcg_cap & MCG_CTL_P) &&
  1838. (data || !msr_info->host_initiated))
  1839. return 1;
  1840. if (data != 0 && data != ~(u64)0)
  1841. return 1;
  1842. vcpu->arch.mcg_ctl = data;
  1843. break;
  1844. default:
  1845. if (msr >= MSR_IA32_MC0_CTL &&
  1846. msr < MSR_IA32_MCx_CTL(bank_num)) {
  1847. u32 offset = msr - MSR_IA32_MC0_CTL;
  1848. /* only 0 or all 1s can be written to IA32_MCi_CTL
  1849. * some Linux kernels though clear bit 10 in bank 4 to
  1850. * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  1851. * this to avoid an uncatched #GP in the guest
  1852. */
  1853. if ((offset & 0x3) == 0 &&
  1854. data != 0 && (data | (1 << 10)) != ~(u64)0)
  1855. return -1;
  1856. if (!msr_info->host_initiated &&
  1857. (offset & 0x3) == 1 && data != 0)
  1858. return -1;
  1859. vcpu->arch.mce_banks[offset] = data;
  1860. break;
  1861. }
  1862. return 1;
  1863. }
  1864. return 0;
  1865. }
  1866. static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  1867. {
  1868. struct kvm *kvm = vcpu->kvm;
  1869. int lm = is_long_mode(vcpu);
  1870. u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  1871. : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  1872. u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  1873. : kvm->arch.xen_hvm_config.blob_size_32;
  1874. u32 page_num = data & ~PAGE_MASK;
  1875. u64 page_addr = data & PAGE_MASK;
  1876. u8 *page;
  1877. int r;
  1878. r = -E2BIG;
  1879. if (page_num >= blob_size)
  1880. goto out;
  1881. r = -ENOMEM;
  1882. page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  1883. if (IS_ERR(page)) {
  1884. r = PTR_ERR(page);
  1885. goto out;
  1886. }
  1887. if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
  1888. goto out_free;
  1889. r = 0;
  1890. out_free:
  1891. kfree(page);
  1892. out:
  1893. return r;
  1894. }
  1895. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  1896. {
  1897. gpa_t gpa = data & ~0x3f;
  1898. /* Bits 3:5 are reserved, Should be zero */
  1899. if (data & 0x38)
  1900. return 1;
  1901. vcpu->arch.apf.msr_val = data;
  1902. if (!(data & KVM_ASYNC_PF_ENABLED)) {
  1903. kvm_clear_async_pf_completion_queue(vcpu);
  1904. kvm_async_pf_hash_reset(vcpu);
  1905. return 0;
  1906. }
  1907. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
  1908. sizeof(u32)))
  1909. return 1;
  1910. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  1911. vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
  1912. kvm_async_pf_wakeup_all(vcpu);
  1913. return 0;
  1914. }
  1915. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  1916. {
  1917. vcpu->arch.pv_time_enabled = false;
  1918. }
  1919. static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
  1920. {
  1921. ++vcpu->stat.tlb_flush;
  1922. kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
  1923. }
  1924. static void record_steal_time(struct kvm_vcpu *vcpu)
  1925. {
  1926. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1927. return;
  1928. if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1929. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  1930. return;
  1931. /*
  1932. * Doing a TLB flush here, on the guest's behalf, can avoid
  1933. * expensive IPIs.
  1934. */
  1935. if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
  1936. kvm_vcpu_flush_tlb(vcpu, false);
  1937. if (vcpu->arch.st.steal.version & 1)
  1938. vcpu->arch.st.steal.version += 1; /* first time write, random junk */
  1939. vcpu->arch.st.steal.version += 1;
  1940. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1941. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1942. smp_wmb();
  1943. vcpu->arch.st.steal.steal += current->sched_info.run_delay -
  1944. vcpu->arch.st.last_steal;
  1945. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1946. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1947. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1948. smp_wmb();
  1949. vcpu->arch.st.steal.version += 1;
  1950. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1951. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1952. }
  1953. int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1954. {
  1955. bool pr = false;
  1956. u32 msr = msr_info->index;
  1957. u64 data = msr_info->data;
  1958. switch (msr) {
  1959. case MSR_AMD64_NB_CFG:
  1960. case MSR_IA32_UCODE_WRITE:
  1961. case MSR_VM_HSAVE_PA:
  1962. case MSR_AMD64_PATCH_LOADER:
  1963. case MSR_AMD64_BU_CFG2:
  1964. case MSR_AMD64_DC_CFG:
  1965. break;
  1966. case MSR_IA32_UCODE_REV:
  1967. if (msr_info->host_initiated)
  1968. vcpu->arch.microcode_version = data;
  1969. break;
  1970. case MSR_EFER:
  1971. return set_efer(vcpu, data);
  1972. case MSR_K7_HWCR:
  1973. data &= ~(u64)0x40; /* ignore flush filter disable */
  1974. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  1975. data &= ~(u64)0x8; /* ignore TLB cache disable */
  1976. data &= ~(u64)0x40000; /* ignore Mc status write enable */
  1977. if (data != 0) {
  1978. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  1979. data);
  1980. return 1;
  1981. }
  1982. break;
  1983. case MSR_FAM10H_MMIO_CONF_BASE:
  1984. if (data != 0) {
  1985. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  1986. "0x%llx\n", data);
  1987. return 1;
  1988. }
  1989. break;
  1990. case MSR_IA32_DEBUGCTLMSR:
  1991. if (!data) {
  1992. /* We support the non-activated case already */
  1993. break;
  1994. } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  1995. /* Values other than LBR and BTF are vendor-specific,
  1996. thus reserved and should throw a #GP */
  1997. return 1;
  1998. }
  1999. vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
  2000. __func__, data);
  2001. break;
  2002. case 0x200 ... 0x2ff:
  2003. return kvm_mtrr_set_msr(vcpu, msr, data);
  2004. case MSR_IA32_APICBASE:
  2005. return kvm_set_apic_base(vcpu, msr_info);
  2006. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2007. return kvm_x2apic_msr_write(vcpu, msr, data);
  2008. case MSR_IA32_TSCDEADLINE:
  2009. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  2010. break;
  2011. case MSR_IA32_TSC_ADJUST:
  2012. if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
  2013. if (!msr_info->host_initiated) {
  2014. s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
  2015. adjust_tsc_offset_guest(vcpu, adj);
  2016. }
  2017. vcpu->arch.ia32_tsc_adjust_msr = data;
  2018. }
  2019. break;
  2020. case MSR_IA32_MISC_ENABLE:
  2021. vcpu->arch.ia32_misc_enable_msr = data;
  2022. break;
  2023. case MSR_IA32_SMBASE:
  2024. if (!msr_info->host_initiated)
  2025. return 1;
  2026. vcpu->arch.smbase = data;
  2027. break;
  2028. case MSR_IA32_TSC:
  2029. kvm_write_tsc(vcpu, msr_info);
  2030. break;
  2031. case MSR_SMI_COUNT:
  2032. if (!msr_info->host_initiated)
  2033. return 1;
  2034. vcpu->arch.smi_count = data;
  2035. break;
  2036. case MSR_KVM_WALL_CLOCK_NEW:
  2037. case MSR_KVM_WALL_CLOCK:
  2038. vcpu->kvm->arch.wall_clock = data;
  2039. kvm_write_wall_clock(vcpu->kvm, data);
  2040. break;
  2041. case MSR_KVM_SYSTEM_TIME_NEW:
  2042. case MSR_KVM_SYSTEM_TIME: {
  2043. struct kvm_arch *ka = &vcpu->kvm->arch;
  2044. kvmclock_reset(vcpu);
  2045. if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
  2046. bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
  2047. if (ka->boot_vcpu_runs_old_kvmclock != tmp)
  2048. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  2049. ka->boot_vcpu_runs_old_kvmclock = tmp;
  2050. }
  2051. vcpu->arch.time = data;
  2052. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  2053. /* we verify if the enable bit is set... */
  2054. if (!(data & 1))
  2055. break;
  2056. if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
  2057. &vcpu->arch.pv_time, data & ~1ULL,
  2058. sizeof(struct pvclock_vcpu_time_info)))
  2059. vcpu->arch.pv_time_enabled = false;
  2060. else
  2061. vcpu->arch.pv_time_enabled = true;
  2062. break;
  2063. }
  2064. case MSR_KVM_ASYNC_PF_EN:
  2065. if (kvm_pv_enable_async_pf(vcpu, data))
  2066. return 1;
  2067. break;
  2068. case MSR_KVM_STEAL_TIME:
  2069. if (unlikely(!sched_info_on()))
  2070. return 1;
  2071. if (data & KVM_STEAL_RESERVED_MASK)
  2072. return 1;
  2073. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  2074. data & KVM_STEAL_VALID_BITS,
  2075. sizeof(struct kvm_steal_time)))
  2076. return 1;
  2077. vcpu->arch.st.msr_val = data;
  2078. if (!(data & KVM_MSR_ENABLED))
  2079. break;
  2080. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2081. break;
  2082. case MSR_KVM_PV_EOI_EN:
  2083. if (kvm_lapic_enable_pv_eoi(vcpu, data))
  2084. return 1;
  2085. break;
  2086. case MSR_IA32_MCG_CTL:
  2087. case MSR_IA32_MCG_STATUS:
  2088. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2089. return set_msr_mce(vcpu, msr_info);
  2090. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  2091. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  2092. pr = true; /* fall through */
  2093. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  2094. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  2095. if (kvm_pmu_is_valid_msr(vcpu, msr))
  2096. return kvm_pmu_set_msr(vcpu, msr_info);
  2097. if (pr || data != 0)
  2098. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  2099. "0x%x data 0x%llx\n", msr, data);
  2100. break;
  2101. case MSR_K7_CLK_CTL:
  2102. /*
  2103. * Ignore all writes to this no longer documented MSR.
  2104. * Writes are only relevant for old K7 processors,
  2105. * all pre-dating SVM, but a recommended workaround from
  2106. * AMD for these chips. It is possible to specify the
  2107. * affected processor models on the command line, hence
  2108. * the need to ignore the workaround.
  2109. */
  2110. break;
  2111. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2112. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  2113. case HV_X64_MSR_CRASH_CTL:
  2114. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  2115. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  2116. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  2117. case HV_X64_MSR_TSC_EMULATION_STATUS:
  2118. return kvm_hv_set_msr_common(vcpu, msr, data,
  2119. msr_info->host_initiated);
  2120. case MSR_IA32_BBL_CR_CTL3:
  2121. /* Drop writes to this legacy MSR -- see rdmsr
  2122. * counterpart for further detail.
  2123. */
  2124. if (report_ignored_msrs)
  2125. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
  2126. msr, data);
  2127. break;
  2128. case MSR_AMD64_OSVW_ID_LENGTH:
  2129. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2130. return 1;
  2131. vcpu->arch.osvw.length = data;
  2132. break;
  2133. case MSR_AMD64_OSVW_STATUS:
  2134. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2135. return 1;
  2136. vcpu->arch.osvw.status = data;
  2137. break;
  2138. case MSR_PLATFORM_INFO:
  2139. if (!msr_info->host_initiated ||
  2140. data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
  2141. (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
  2142. cpuid_fault_enabled(vcpu)))
  2143. return 1;
  2144. vcpu->arch.msr_platform_info = data;
  2145. break;
  2146. case MSR_MISC_FEATURES_ENABLES:
  2147. if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
  2148. (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
  2149. !supports_cpuid_fault(vcpu)))
  2150. return 1;
  2151. vcpu->arch.msr_misc_features_enables = data;
  2152. break;
  2153. default:
  2154. if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  2155. return xen_hvm_config(vcpu, data);
  2156. if (kvm_pmu_is_valid_msr(vcpu, msr))
  2157. return kvm_pmu_set_msr(vcpu, msr_info);
  2158. if (!ignore_msrs) {
  2159. vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
  2160. msr, data);
  2161. return 1;
  2162. } else {
  2163. if (report_ignored_msrs)
  2164. vcpu_unimpl(vcpu,
  2165. "ignored wrmsr: 0x%x data 0x%llx\n",
  2166. msr, data);
  2167. break;
  2168. }
  2169. }
  2170. return 0;
  2171. }
  2172. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  2173. /*
  2174. * Reads an msr value (of 'msr_index') into 'pdata'.
  2175. * Returns 0 on success, non-0 otherwise.
  2176. * Assumes vcpu_load() was already called.
  2177. */
  2178. int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  2179. {
  2180. return kvm_x86_ops->get_msr(vcpu, msr);
  2181. }
  2182. EXPORT_SYMBOL_GPL(kvm_get_msr);
  2183. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
  2184. {
  2185. u64 data;
  2186. u64 mcg_cap = vcpu->arch.mcg_cap;
  2187. unsigned bank_num = mcg_cap & 0xff;
  2188. switch (msr) {
  2189. case MSR_IA32_P5_MC_ADDR:
  2190. case MSR_IA32_P5_MC_TYPE:
  2191. data = 0;
  2192. break;
  2193. case MSR_IA32_MCG_CAP:
  2194. data = vcpu->arch.mcg_cap;
  2195. break;
  2196. case MSR_IA32_MCG_CTL:
  2197. if (!(mcg_cap & MCG_CTL_P) && !host)
  2198. return 1;
  2199. data = vcpu->arch.mcg_ctl;
  2200. break;
  2201. case MSR_IA32_MCG_STATUS:
  2202. data = vcpu->arch.mcg_status;
  2203. break;
  2204. default:
  2205. if (msr >= MSR_IA32_MC0_CTL &&
  2206. msr < MSR_IA32_MCx_CTL(bank_num)) {
  2207. u32 offset = msr - MSR_IA32_MC0_CTL;
  2208. data = vcpu->arch.mce_banks[offset];
  2209. break;
  2210. }
  2211. return 1;
  2212. }
  2213. *pdata = data;
  2214. return 0;
  2215. }
  2216. int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  2217. {
  2218. switch (msr_info->index) {
  2219. case MSR_IA32_PLATFORM_ID:
  2220. case MSR_IA32_EBL_CR_POWERON:
  2221. case MSR_IA32_DEBUGCTLMSR:
  2222. case MSR_IA32_LASTBRANCHFROMIP:
  2223. case MSR_IA32_LASTBRANCHTOIP:
  2224. case MSR_IA32_LASTINTFROMIP:
  2225. case MSR_IA32_LASTINTTOIP:
  2226. case MSR_K8_SYSCFG:
  2227. case MSR_K8_TSEG_ADDR:
  2228. case MSR_K8_TSEG_MASK:
  2229. case MSR_K7_HWCR:
  2230. case MSR_VM_HSAVE_PA:
  2231. case MSR_K8_INT_PENDING_MSG:
  2232. case MSR_AMD64_NB_CFG:
  2233. case MSR_FAM10H_MMIO_CONF_BASE:
  2234. case MSR_AMD64_BU_CFG2:
  2235. case MSR_IA32_PERF_CTL:
  2236. case MSR_AMD64_DC_CFG:
  2237. msr_info->data = 0;
  2238. break;
  2239. case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
  2240. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  2241. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  2242. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  2243. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  2244. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2245. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2246. msr_info->data = 0;
  2247. break;
  2248. case MSR_IA32_UCODE_REV:
  2249. msr_info->data = vcpu->arch.microcode_version;
  2250. break;
  2251. case MSR_IA32_TSC:
  2252. msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
  2253. break;
  2254. case MSR_MTRRcap:
  2255. case 0x200 ... 0x2ff:
  2256. return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
  2257. case 0xcd: /* fsb frequency */
  2258. msr_info->data = 3;
  2259. break;
  2260. /*
  2261. * MSR_EBC_FREQUENCY_ID
  2262. * Conservative value valid for even the basic CPU models.
  2263. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  2264. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  2265. * and 266MHz for model 3, or 4. Set Core Clock
  2266. * Frequency to System Bus Frequency Ratio to 1 (bits
  2267. * 31:24) even though these are only valid for CPU
  2268. * models > 2, however guests may end up dividing or
  2269. * multiplying by zero otherwise.
  2270. */
  2271. case MSR_EBC_FREQUENCY_ID:
  2272. msr_info->data = 1 << 24;
  2273. break;
  2274. case MSR_IA32_APICBASE:
  2275. msr_info->data = kvm_get_apic_base(vcpu);
  2276. break;
  2277. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2278. return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
  2279. break;
  2280. case MSR_IA32_TSCDEADLINE:
  2281. msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
  2282. break;
  2283. case MSR_IA32_TSC_ADJUST:
  2284. msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
  2285. break;
  2286. case MSR_IA32_MISC_ENABLE:
  2287. msr_info->data = vcpu->arch.ia32_misc_enable_msr;
  2288. break;
  2289. case MSR_IA32_SMBASE:
  2290. if (!msr_info->host_initiated)
  2291. return 1;
  2292. msr_info->data = vcpu->arch.smbase;
  2293. break;
  2294. case MSR_SMI_COUNT:
  2295. msr_info->data = vcpu->arch.smi_count;
  2296. break;
  2297. case MSR_IA32_PERF_STATUS:
  2298. /* TSC increment by tick */
  2299. msr_info->data = 1000ULL;
  2300. /* CPU multiplier */
  2301. msr_info->data |= (((uint64_t)4ULL) << 40);
  2302. break;
  2303. case MSR_EFER:
  2304. msr_info->data = vcpu->arch.efer;
  2305. break;
  2306. case MSR_KVM_WALL_CLOCK:
  2307. case MSR_KVM_WALL_CLOCK_NEW:
  2308. msr_info->data = vcpu->kvm->arch.wall_clock;
  2309. break;
  2310. case MSR_KVM_SYSTEM_TIME:
  2311. case MSR_KVM_SYSTEM_TIME_NEW:
  2312. msr_info->data = vcpu->arch.time;
  2313. break;
  2314. case MSR_KVM_ASYNC_PF_EN:
  2315. msr_info->data = vcpu->arch.apf.msr_val;
  2316. break;
  2317. case MSR_KVM_STEAL_TIME:
  2318. msr_info->data = vcpu->arch.st.msr_val;
  2319. break;
  2320. case MSR_KVM_PV_EOI_EN:
  2321. msr_info->data = vcpu->arch.pv_eoi.msr_val;
  2322. break;
  2323. case MSR_IA32_P5_MC_ADDR:
  2324. case MSR_IA32_P5_MC_TYPE:
  2325. case MSR_IA32_MCG_CAP:
  2326. case MSR_IA32_MCG_CTL:
  2327. case MSR_IA32_MCG_STATUS:
  2328. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2329. return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
  2330. msr_info->host_initiated);
  2331. case MSR_K7_CLK_CTL:
  2332. /*
  2333. * Provide expected ramp-up count for K7. All other
  2334. * are set to zero, indicating minimum divisors for
  2335. * every field.
  2336. *
  2337. * This prevents guest kernels on AMD host with CPU
  2338. * type 6, model 8 and higher from exploding due to
  2339. * the rdmsr failing.
  2340. */
  2341. msr_info->data = 0x20000000;
  2342. break;
  2343. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2344. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  2345. case HV_X64_MSR_CRASH_CTL:
  2346. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  2347. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  2348. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  2349. case HV_X64_MSR_TSC_EMULATION_STATUS:
  2350. return kvm_hv_get_msr_common(vcpu,
  2351. msr_info->index, &msr_info->data,
  2352. msr_info->host_initiated);
  2353. break;
  2354. case MSR_IA32_BBL_CR_CTL3:
  2355. /* This legacy MSR exists but isn't fully documented in current
  2356. * silicon. It is however accessed by winxp in very narrow
  2357. * scenarios where it sets bit #19, itself documented as
  2358. * a "reserved" bit. Best effort attempt to source coherent
  2359. * read data here should the balance of the register be
  2360. * interpreted by the guest:
  2361. *
  2362. * L2 cache control register 3: 64GB range, 256KB size,
  2363. * enabled, latency 0x1, configured
  2364. */
  2365. msr_info->data = 0xbe702111;
  2366. break;
  2367. case MSR_AMD64_OSVW_ID_LENGTH:
  2368. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2369. return 1;
  2370. msr_info->data = vcpu->arch.osvw.length;
  2371. break;
  2372. case MSR_AMD64_OSVW_STATUS:
  2373. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2374. return 1;
  2375. msr_info->data = vcpu->arch.osvw.status;
  2376. break;
  2377. case MSR_PLATFORM_INFO:
  2378. msr_info->data = vcpu->arch.msr_platform_info;
  2379. break;
  2380. case MSR_MISC_FEATURES_ENABLES:
  2381. msr_info->data = vcpu->arch.msr_misc_features_enables;
  2382. break;
  2383. default:
  2384. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2385. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2386. if (!ignore_msrs) {
  2387. vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
  2388. msr_info->index);
  2389. return 1;
  2390. } else {
  2391. if (report_ignored_msrs)
  2392. vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
  2393. msr_info->index);
  2394. msr_info->data = 0;
  2395. }
  2396. break;
  2397. }
  2398. return 0;
  2399. }
  2400. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  2401. /*
  2402. * Read or write a bunch of msrs. All parameters are kernel addresses.
  2403. *
  2404. * @return number of msrs set successfully.
  2405. */
  2406. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  2407. struct kvm_msr_entry *entries,
  2408. int (*do_msr)(struct kvm_vcpu *vcpu,
  2409. unsigned index, u64 *data))
  2410. {
  2411. int i;
  2412. for (i = 0; i < msrs->nmsrs; ++i)
  2413. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  2414. break;
  2415. return i;
  2416. }
  2417. /*
  2418. * Read or write a bunch of msrs. Parameters are user addresses.
  2419. *
  2420. * @return number of msrs set successfully.
  2421. */
  2422. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  2423. int (*do_msr)(struct kvm_vcpu *vcpu,
  2424. unsigned index, u64 *data),
  2425. int writeback)
  2426. {
  2427. struct kvm_msrs msrs;
  2428. struct kvm_msr_entry *entries;
  2429. int r, n;
  2430. unsigned size;
  2431. r = -EFAULT;
  2432. if (copy_from_user(&msrs, user_msrs, sizeof msrs))
  2433. goto out;
  2434. r = -E2BIG;
  2435. if (msrs.nmsrs >= MAX_IO_MSRS)
  2436. goto out;
  2437. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  2438. entries = memdup_user(user_msrs->entries, size);
  2439. if (IS_ERR(entries)) {
  2440. r = PTR_ERR(entries);
  2441. goto out;
  2442. }
  2443. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  2444. if (r < 0)
  2445. goto out_free;
  2446. r = -EFAULT;
  2447. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  2448. goto out_free;
  2449. r = n;
  2450. out_free:
  2451. kfree(entries);
  2452. out:
  2453. return r;
  2454. }
  2455. static inline bool kvm_can_mwait_in_guest(void)
  2456. {
  2457. return boot_cpu_has(X86_FEATURE_MWAIT) &&
  2458. !boot_cpu_has_bug(X86_BUG_MONITOR) &&
  2459. boot_cpu_has(X86_FEATURE_ARAT);
  2460. }
  2461. int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  2462. {
  2463. int r = 0;
  2464. switch (ext) {
  2465. case KVM_CAP_IRQCHIP:
  2466. case KVM_CAP_HLT:
  2467. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  2468. case KVM_CAP_SET_TSS_ADDR:
  2469. case KVM_CAP_EXT_CPUID:
  2470. case KVM_CAP_EXT_EMUL_CPUID:
  2471. case KVM_CAP_CLOCKSOURCE:
  2472. case KVM_CAP_PIT:
  2473. case KVM_CAP_NOP_IO_DELAY:
  2474. case KVM_CAP_MP_STATE:
  2475. case KVM_CAP_SYNC_MMU:
  2476. case KVM_CAP_USER_NMI:
  2477. case KVM_CAP_REINJECT_CONTROL:
  2478. case KVM_CAP_IRQ_INJECT_STATUS:
  2479. case KVM_CAP_IOEVENTFD:
  2480. case KVM_CAP_IOEVENTFD_NO_LENGTH:
  2481. case KVM_CAP_PIT2:
  2482. case KVM_CAP_PIT_STATE2:
  2483. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  2484. case KVM_CAP_XEN_HVM:
  2485. case KVM_CAP_VCPU_EVENTS:
  2486. case KVM_CAP_HYPERV:
  2487. case KVM_CAP_HYPERV_VAPIC:
  2488. case KVM_CAP_HYPERV_SPIN:
  2489. case KVM_CAP_HYPERV_SYNIC:
  2490. case KVM_CAP_HYPERV_SYNIC2:
  2491. case KVM_CAP_HYPERV_VP_INDEX:
  2492. case KVM_CAP_HYPERV_EVENTFD:
  2493. case KVM_CAP_HYPERV_TLBFLUSH:
  2494. case KVM_CAP_PCI_SEGMENT:
  2495. case KVM_CAP_DEBUGREGS:
  2496. case KVM_CAP_X86_ROBUST_SINGLESTEP:
  2497. case KVM_CAP_XSAVE:
  2498. case KVM_CAP_ASYNC_PF:
  2499. case KVM_CAP_GET_TSC_KHZ:
  2500. case KVM_CAP_KVMCLOCK_CTRL:
  2501. case KVM_CAP_READONLY_MEM:
  2502. case KVM_CAP_HYPERV_TIME:
  2503. case KVM_CAP_IOAPIC_POLARITY_IGNORED:
  2504. case KVM_CAP_TSC_DEADLINE_TIMER:
  2505. case KVM_CAP_ENABLE_CAP_VM:
  2506. case KVM_CAP_DISABLE_QUIRKS:
  2507. case KVM_CAP_SET_BOOT_CPU_ID:
  2508. case KVM_CAP_SPLIT_IRQCHIP:
  2509. case KVM_CAP_IMMEDIATE_EXIT:
  2510. case KVM_CAP_GET_MSR_FEATURES:
  2511. r = 1;
  2512. break;
  2513. case KVM_CAP_SYNC_REGS:
  2514. r = KVM_SYNC_X86_VALID_FIELDS;
  2515. break;
  2516. case KVM_CAP_ADJUST_CLOCK:
  2517. r = KVM_CLOCK_TSC_STABLE;
  2518. break;
  2519. case KVM_CAP_X86_DISABLE_EXITS:
  2520. r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE;
  2521. if(kvm_can_mwait_in_guest())
  2522. r |= KVM_X86_DISABLE_EXITS_MWAIT;
  2523. break;
  2524. case KVM_CAP_X86_SMM:
  2525. /* SMBASE is usually relocated above 1M on modern chipsets,
  2526. * and SMM handlers might indeed rely on 4G segment limits,
  2527. * so do not report SMM to be available if real mode is
  2528. * emulated via vm86 mode. Still, do not go to great lengths
  2529. * to avoid userspace's usage of the feature, because it is a
  2530. * fringe case that is not enabled except via specific settings
  2531. * of the module parameters.
  2532. */
  2533. r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
  2534. break;
  2535. case KVM_CAP_VAPIC:
  2536. r = !kvm_x86_ops->cpu_has_accelerated_tpr();
  2537. break;
  2538. case KVM_CAP_NR_VCPUS:
  2539. r = KVM_SOFT_MAX_VCPUS;
  2540. break;
  2541. case KVM_CAP_MAX_VCPUS:
  2542. r = KVM_MAX_VCPUS;
  2543. break;
  2544. case KVM_CAP_NR_MEMSLOTS:
  2545. r = KVM_USER_MEM_SLOTS;
  2546. break;
  2547. case KVM_CAP_PV_MMU: /* obsolete */
  2548. r = 0;
  2549. break;
  2550. case KVM_CAP_MCE:
  2551. r = KVM_MAX_MCE_BANKS;
  2552. break;
  2553. case KVM_CAP_XCRS:
  2554. r = boot_cpu_has(X86_FEATURE_XSAVE);
  2555. break;
  2556. case KVM_CAP_TSC_CONTROL:
  2557. r = kvm_has_tsc_control;
  2558. break;
  2559. case KVM_CAP_X2APIC_API:
  2560. r = KVM_X2APIC_API_VALID_FLAGS;
  2561. break;
  2562. case KVM_CAP_NESTED_STATE:
  2563. r = kvm_x86_ops->get_nested_state ?
  2564. kvm_x86_ops->get_nested_state(NULL, 0, 0) : 0;
  2565. break;
  2566. default:
  2567. break;
  2568. }
  2569. return r;
  2570. }
  2571. long kvm_arch_dev_ioctl(struct file *filp,
  2572. unsigned int ioctl, unsigned long arg)
  2573. {
  2574. void __user *argp = (void __user *)arg;
  2575. long r;
  2576. switch (ioctl) {
  2577. case KVM_GET_MSR_INDEX_LIST: {
  2578. struct kvm_msr_list __user *user_msr_list = argp;
  2579. struct kvm_msr_list msr_list;
  2580. unsigned n;
  2581. r = -EFAULT;
  2582. if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
  2583. goto out;
  2584. n = msr_list.nmsrs;
  2585. msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
  2586. if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
  2587. goto out;
  2588. r = -E2BIG;
  2589. if (n < msr_list.nmsrs)
  2590. goto out;
  2591. r = -EFAULT;
  2592. if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  2593. num_msrs_to_save * sizeof(u32)))
  2594. goto out;
  2595. if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
  2596. &emulated_msrs,
  2597. num_emulated_msrs * sizeof(u32)))
  2598. goto out;
  2599. r = 0;
  2600. break;
  2601. }
  2602. case KVM_GET_SUPPORTED_CPUID:
  2603. case KVM_GET_EMULATED_CPUID: {
  2604. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2605. struct kvm_cpuid2 cpuid;
  2606. r = -EFAULT;
  2607. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2608. goto out;
  2609. r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
  2610. ioctl);
  2611. if (r)
  2612. goto out;
  2613. r = -EFAULT;
  2614. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  2615. goto out;
  2616. r = 0;
  2617. break;
  2618. }
  2619. case KVM_X86_GET_MCE_CAP_SUPPORTED: {
  2620. r = -EFAULT;
  2621. if (copy_to_user(argp, &kvm_mce_cap_supported,
  2622. sizeof(kvm_mce_cap_supported)))
  2623. goto out;
  2624. r = 0;
  2625. break;
  2626. case KVM_GET_MSR_FEATURE_INDEX_LIST: {
  2627. struct kvm_msr_list __user *user_msr_list = argp;
  2628. struct kvm_msr_list msr_list;
  2629. unsigned int n;
  2630. r = -EFAULT;
  2631. if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
  2632. goto out;
  2633. n = msr_list.nmsrs;
  2634. msr_list.nmsrs = num_msr_based_features;
  2635. if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
  2636. goto out;
  2637. r = -E2BIG;
  2638. if (n < msr_list.nmsrs)
  2639. goto out;
  2640. r = -EFAULT;
  2641. if (copy_to_user(user_msr_list->indices, &msr_based_features,
  2642. num_msr_based_features * sizeof(u32)))
  2643. goto out;
  2644. r = 0;
  2645. break;
  2646. }
  2647. case KVM_GET_MSRS:
  2648. r = msr_io(NULL, argp, do_get_msr_feature, 1);
  2649. break;
  2650. }
  2651. default:
  2652. r = -EINVAL;
  2653. }
  2654. out:
  2655. return r;
  2656. }
  2657. static void wbinvd_ipi(void *garbage)
  2658. {
  2659. wbinvd();
  2660. }
  2661. static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  2662. {
  2663. return kvm_arch_has_noncoherent_dma(vcpu->kvm);
  2664. }
  2665. void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  2666. {
  2667. /* Address WBINVD may be executed by guest */
  2668. if (need_emulate_wbinvd(vcpu)) {
  2669. if (kvm_x86_ops->has_wbinvd_exit())
  2670. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  2671. else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  2672. smp_call_function_single(vcpu->cpu,
  2673. wbinvd_ipi, NULL, 1);
  2674. }
  2675. kvm_x86_ops->vcpu_load(vcpu, cpu);
  2676. /* Apply any externally detected TSC adjustments (due to suspend) */
  2677. if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
  2678. adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  2679. vcpu->arch.tsc_offset_adjustment = 0;
  2680. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2681. }
  2682. if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
  2683. s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
  2684. rdtsc() - vcpu->arch.last_host_tsc;
  2685. if (tsc_delta < 0)
  2686. mark_tsc_unstable("KVM discovered backwards TSC");
  2687. if (kvm_check_tsc_unstable()) {
  2688. u64 offset = kvm_compute_tsc_offset(vcpu,
  2689. vcpu->arch.last_guest_tsc);
  2690. kvm_vcpu_write_tsc_offset(vcpu, offset);
  2691. vcpu->arch.tsc_catchup = 1;
  2692. }
  2693. if (kvm_lapic_hv_timer_in_use(vcpu))
  2694. kvm_lapic_restart_hv_timer(vcpu);
  2695. /*
  2696. * On a host with synchronized TSC, there is no need to update
  2697. * kvmclock on vcpu->cpu migration
  2698. */
  2699. if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
  2700. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  2701. if (vcpu->cpu != cpu)
  2702. kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
  2703. vcpu->cpu = cpu;
  2704. }
  2705. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2706. }
  2707. static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
  2708. {
  2709. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  2710. return;
  2711. vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
  2712. kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2713. &vcpu->arch.st.steal.preempted,
  2714. offsetof(struct kvm_steal_time, preempted),
  2715. sizeof(vcpu->arch.st.steal.preempted));
  2716. }
  2717. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  2718. {
  2719. int idx;
  2720. if (vcpu->preempted)
  2721. vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
  2722. /*
  2723. * Disable page faults because we're in atomic context here.
  2724. * kvm_write_guest_offset_cached() would call might_fault()
  2725. * that relies on pagefault_disable() to tell if there's a
  2726. * bug. NOTE: the write to guest memory may not go through if
  2727. * during postcopy live migration or if there's heavy guest
  2728. * paging.
  2729. */
  2730. pagefault_disable();
  2731. /*
  2732. * kvm_memslots() will be called by
  2733. * kvm_write_guest_offset_cached() so take the srcu lock.
  2734. */
  2735. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2736. kvm_steal_time_set_preempted(vcpu);
  2737. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2738. pagefault_enable();
  2739. kvm_x86_ops->vcpu_put(vcpu);
  2740. vcpu->arch.last_host_tsc = rdtsc();
  2741. /*
  2742. * If userspace has set any breakpoints or watchpoints, dr6 is restored
  2743. * on every vmexit, but if not, we might have a stale dr6 from the
  2744. * guest. do_debug expects dr6 to be cleared after it runs, do the same.
  2745. */
  2746. set_debugreg(0, 6);
  2747. }
  2748. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2749. struct kvm_lapic_state *s)
  2750. {
  2751. if (vcpu->arch.apicv_active)
  2752. kvm_x86_ops->sync_pir_to_irr(vcpu);
  2753. return kvm_apic_get_state(vcpu, s);
  2754. }
  2755. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2756. struct kvm_lapic_state *s)
  2757. {
  2758. int r;
  2759. r = kvm_apic_set_state(vcpu, s);
  2760. if (r)
  2761. return r;
  2762. update_cr8_intercept(vcpu);
  2763. return 0;
  2764. }
  2765. static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
  2766. {
  2767. return (!lapic_in_kernel(vcpu) ||
  2768. kvm_apic_accept_pic_intr(vcpu));
  2769. }
  2770. /*
  2771. * if userspace requested an interrupt window, check that the
  2772. * interrupt window is open.
  2773. *
  2774. * No need to exit to userspace if we already have an interrupt queued.
  2775. */
  2776. static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
  2777. {
  2778. return kvm_arch_interrupt_allowed(vcpu) &&
  2779. !kvm_cpu_has_interrupt(vcpu) &&
  2780. !kvm_event_needs_reinjection(vcpu) &&
  2781. kvm_cpu_accept_dm_intr(vcpu);
  2782. }
  2783. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2784. struct kvm_interrupt *irq)
  2785. {
  2786. if (irq->irq >= KVM_NR_INTERRUPTS)
  2787. return -EINVAL;
  2788. if (!irqchip_in_kernel(vcpu->kvm)) {
  2789. kvm_queue_interrupt(vcpu, irq->irq, false);
  2790. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2791. return 0;
  2792. }
  2793. /*
  2794. * With in-kernel LAPIC, we only use this to inject EXTINT, so
  2795. * fail for in-kernel 8259.
  2796. */
  2797. if (pic_in_kernel(vcpu->kvm))
  2798. return -ENXIO;
  2799. if (vcpu->arch.pending_external_vector != -1)
  2800. return -EEXIST;
  2801. vcpu->arch.pending_external_vector = irq->irq;
  2802. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2803. return 0;
  2804. }
  2805. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2806. {
  2807. kvm_inject_nmi(vcpu);
  2808. return 0;
  2809. }
  2810. static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
  2811. {
  2812. kvm_make_request(KVM_REQ_SMI, vcpu);
  2813. return 0;
  2814. }
  2815. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2816. struct kvm_tpr_access_ctl *tac)
  2817. {
  2818. if (tac->flags)
  2819. return -EINVAL;
  2820. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2821. return 0;
  2822. }
  2823. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2824. u64 mcg_cap)
  2825. {
  2826. int r;
  2827. unsigned bank_num = mcg_cap & 0xff, bank;
  2828. r = -EINVAL;
  2829. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2830. goto out;
  2831. if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
  2832. goto out;
  2833. r = 0;
  2834. vcpu->arch.mcg_cap = mcg_cap;
  2835. /* Init IA32_MCG_CTL to all 1s */
  2836. if (mcg_cap & MCG_CTL_P)
  2837. vcpu->arch.mcg_ctl = ~(u64)0;
  2838. /* Init IA32_MCi_CTL to all 1s */
  2839. for (bank = 0; bank < bank_num; bank++)
  2840. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2841. if (kvm_x86_ops->setup_mce)
  2842. kvm_x86_ops->setup_mce(vcpu);
  2843. out:
  2844. return r;
  2845. }
  2846. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2847. struct kvm_x86_mce *mce)
  2848. {
  2849. u64 mcg_cap = vcpu->arch.mcg_cap;
  2850. unsigned bank_num = mcg_cap & 0xff;
  2851. u64 *banks = vcpu->arch.mce_banks;
  2852. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2853. return -EINVAL;
  2854. /*
  2855. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2856. * reporting is disabled
  2857. */
  2858. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2859. vcpu->arch.mcg_ctl != ~(u64)0)
  2860. return 0;
  2861. banks += 4 * mce->bank;
  2862. /*
  2863. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2864. * reporting is disabled for the bank
  2865. */
  2866. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2867. return 0;
  2868. if (mce->status & MCI_STATUS_UC) {
  2869. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2870. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2871. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2872. return 0;
  2873. }
  2874. if (banks[1] & MCI_STATUS_VAL)
  2875. mce->status |= MCI_STATUS_OVER;
  2876. banks[2] = mce->addr;
  2877. banks[3] = mce->misc;
  2878. vcpu->arch.mcg_status = mce->mcg_status;
  2879. banks[1] = mce->status;
  2880. kvm_queue_exception(vcpu, MC_VECTOR);
  2881. } else if (!(banks[1] & MCI_STATUS_VAL)
  2882. || !(banks[1] & MCI_STATUS_UC)) {
  2883. if (banks[1] & MCI_STATUS_VAL)
  2884. mce->status |= MCI_STATUS_OVER;
  2885. banks[2] = mce->addr;
  2886. banks[3] = mce->misc;
  2887. banks[1] = mce->status;
  2888. } else
  2889. banks[1] |= MCI_STATUS_OVER;
  2890. return 0;
  2891. }
  2892. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2893. struct kvm_vcpu_events *events)
  2894. {
  2895. process_nmi(vcpu);
  2896. /*
  2897. * FIXME: pass injected and pending separately. This is only
  2898. * needed for nested virtualization, whose state cannot be
  2899. * migrated yet. For now we can combine them.
  2900. */
  2901. events->exception.injected =
  2902. (vcpu->arch.exception.pending ||
  2903. vcpu->arch.exception.injected) &&
  2904. !kvm_exception_is_soft(vcpu->arch.exception.nr);
  2905. events->exception.nr = vcpu->arch.exception.nr;
  2906. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  2907. events->exception.pad = 0;
  2908. events->exception.error_code = vcpu->arch.exception.error_code;
  2909. events->interrupt.injected =
  2910. vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
  2911. events->interrupt.nr = vcpu->arch.interrupt.nr;
  2912. events->interrupt.soft = 0;
  2913. events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  2914. events->nmi.injected = vcpu->arch.nmi_injected;
  2915. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  2916. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  2917. events->nmi.pad = 0;
  2918. events->sipi_vector = 0; /* never valid when reporting to user space */
  2919. events->smi.smm = is_smm(vcpu);
  2920. events->smi.pending = vcpu->arch.smi_pending;
  2921. events->smi.smm_inside_nmi =
  2922. !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
  2923. events->smi.latched_init = kvm_lapic_latched_init(vcpu);
  2924. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  2925. | KVM_VCPUEVENT_VALID_SHADOW
  2926. | KVM_VCPUEVENT_VALID_SMM);
  2927. memset(&events->reserved, 0, sizeof(events->reserved));
  2928. }
  2929. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
  2930. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  2931. struct kvm_vcpu_events *events)
  2932. {
  2933. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  2934. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2935. | KVM_VCPUEVENT_VALID_SHADOW
  2936. | KVM_VCPUEVENT_VALID_SMM))
  2937. return -EINVAL;
  2938. if (events->exception.injected &&
  2939. (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
  2940. is_guest_mode(vcpu)))
  2941. return -EINVAL;
  2942. /* INITs are latched while in SMM */
  2943. if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
  2944. (events->smi.smm || events->smi.pending) &&
  2945. vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
  2946. return -EINVAL;
  2947. process_nmi(vcpu);
  2948. vcpu->arch.exception.injected = false;
  2949. vcpu->arch.exception.pending = events->exception.injected;
  2950. vcpu->arch.exception.nr = events->exception.nr;
  2951. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  2952. vcpu->arch.exception.error_code = events->exception.error_code;
  2953. vcpu->arch.interrupt.injected = events->interrupt.injected;
  2954. vcpu->arch.interrupt.nr = events->interrupt.nr;
  2955. vcpu->arch.interrupt.soft = events->interrupt.soft;
  2956. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  2957. kvm_x86_ops->set_interrupt_shadow(vcpu,
  2958. events->interrupt.shadow);
  2959. vcpu->arch.nmi_injected = events->nmi.injected;
  2960. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  2961. vcpu->arch.nmi_pending = events->nmi.pending;
  2962. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  2963. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  2964. lapic_in_kernel(vcpu))
  2965. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  2966. if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
  2967. u32 hflags = vcpu->arch.hflags;
  2968. if (events->smi.smm)
  2969. hflags |= HF_SMM_MASK;
  2970. else
  2971. hflags &= ~HF_SMM_MASK;
  2972. kvm_set_hflags(vcpu, hflags);
  2973. vcpu->arch.smi_pending = events->smi.pending;
  2974. if (events->smi.smm) {
  2975. if (events->smi.smm_inside_nmi)
  2976. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  2977. else
  2978. vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
  2979. if (lapic_in_kernel(vcpu)) {
  2980. if (events->smi.latched_init)
  2981. set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2982. else
  2983. clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2984. }
  2985. }
  2986. }
  2987. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2988. return 0;
  2989. }
  2990. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  2991. struct kvm_debugregs *dbgregs)
  2992. {
  2993. unsigned long val;
  2994. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  2995. kvm_get_dr(vcpu, 6, &val);
  2996. dbgregs->dr6 = val;
  2997. dbgregs->dr7 = vcpu->arch.dr7;
  2998. dbgregs->flags = 0;
  2999. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  3000. }
  3001. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  3002. struct kvm_debugregs *dbgregs)
  3003. {
  3004. if (dbgregs->flags)
  3005. return -EINVAL;
  3006. if (dbgregs->dr6 & ~0xffffffffull)
  3007. return -EINVAL;
  3008. if (dbgregs->dr7 & ~0xffffffffull)
  3009. return -EINVAL;
  3010. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  3011. kvm_update_dr0123(vcpu);
  3012. vcpu->arch.dr6 = dbgregs->dr6;
  3013. kvm_update_dr6(vcpu);
  3014. vcpu->arch.dr7 = dbgregs->dr7;
  3015. kvm_update_dr7(vcpu);
  3016. return 0;
  3017. }
  3018. #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
  3019. static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
  3020. {
  3021. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  3022. u64 xstate_bv = xsave->header.xfeatures;
  3023. u64 valid;
  3024. /*
  3025. * Copy legacy XSAVE area, to avoid complications with CPUID
  3026. * leaves 0 and 1 in the loop below.
  3027. */
  3028. memcpy(dest, xsave, XSAVE_HDR_OFFSET);
  3029. /* Set XSTATE_BV */
  3030. xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
  3031. *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
  3032. /*
  3033. * Copy each region from the possibly compacted offset to the
  3034. * non-compacted offset.
  3035. */
  3036. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  3037. while (valid) {
  3038. u64 feature = valid & -valid;
  3039. int index = fls64(feature) - 1;
  3040. void *src = get_xsave_addr(xsave, feature);
  3041. if (src) {
  3042. u32 size, offset, ecx, edx;
  3043. cpuid_count(XSTATE_CPUID, index,
  3044. &size, &offset, &ecx, &edx);
  3045. if (feature == XFEATURE_MASK_PKRU)
  3046. memcpy(dest + offset, &vcpu->arch.pkru,
  3047. sizeof(vcpu->arch.pkru));
  3048. else
  3049. memcpy(dest + offset, src, size);
  3050. }
  3051. valid -= feature;
  3052. }
  3053. }
  3054. static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
  3055. {
  3056. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  3057. u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
  3058. u64 valid;
  3059. /*
  3060. * Copy legacy XSAVE area, to avoid complications with CPUID
  3061. * leaves 0 and 1 in the loop below.
  3062. */
  3063. memcpy(xsave, src, XSAVE_HDR_OFFSET);
  3064. /* Set XSTATE_BV and possibly XCOMP_BV. */
  3065. xsave->header.xfeatures = xstate_bv;
  3066. if (boot_cpu_has(X86_FEATURE_XSAVES))
  3067. xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
  3068. /*
  3069. * Copy each region from the non-compacted offset to the
  3070. * possibly compacted offset.
  3071. */
  3072. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  3073. while (valid) {
  3074. u64 feature = valid & -valid;
  3075. int index = fls64(feature) - 1;
  3076. void *dest = get_xsave_addr(xsave, feature);
  3077. if (dest) {
  3078. u32 size, offset, ecx, edx;
  3079. cpuid_count(XSTATE_CPUID, index,
  3080. &size, &offset, &ecx, &edx);
  3081. if (feature == XFEATURE_MASK_PKRU)
  3082. memcpy(&vcpu->arch.pkru, src + offset,
  3083. sizeof(vcpu->arch.pkru));
  3084. else
  3085. memcpy(dest, src + offset, size);
  3086. }
  3087. valid -= feature;
  3088. }
  3089. }
  3090. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  3091. struct kvm_xsave *guest_xsave)
  3092. {
  3093. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  3094. memset(guest_xsave, 0, sizeof(struct kvm_xsave));
  3095. fill_xsave((u8 *) guest_xsave->region, vcpu);
  3096. } else {
  3097. memcpy(guest_xsave->region,
  3098. &vcpu->arch.guest_fpu.state.fxsave,
  3099. sizeof(struct fxregs_state));
  3100. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  3101. XFEATURE_MASK_FPSSE;
  3102. }
  3103. }
  3104. #define XSAVE_MXCSR_OFFSET 24
  3105. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  3106. struct kvm_xsave *guest_xsave)
  3107. {
  3108. u64 xstate_bv =
  3109. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  3110. u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
  3111. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  3112. /*
  3113. * Here we allow setting states that are not present in
  3114. * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
  3115. * with old userspace.
  3116. */
  3117. if (xstate_bv & ~kvm_supported_xcr0() ||
  3118. mxcsr & ~mxcsr_feature_mask)
  3119. return -EINVAL;
  3120. load_xsave(vcpu, (u8 *)guest_xsave->region);
  3121. } else {
  3122. if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
  3123. mxcsr & ~mxcsr_feature_mask)
  3124. return -EINVAL;
  3125. memcpy(&vcpu->arch.guest_fpu.state.fxsave,
  3126. guest_xsave->region, sizeof(struct fxregs_state));
  3127. }
  3128. return 0;
  3129. }
  3130. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  3131. struct kvm_xcrs *guest_xcrs)
  3132. {
  3133. if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
  3134. guest_xcrs->nr_xcrs = 0;
  3135. return;
  3136. }
  3137. guest_xcrs->nr_xcrs = 1;
  3138. guest_xcrs->flags = 0;
  3139. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  3140. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  3141. }
  3142. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  3143. struct kvm_xcrs *guest_xcrs)
  3144. {
  3145. int i, r = 0;
  3146. if (!boot_cpu_has(X86_FEATURE_XSAVE))
  3147. return -EINVAL;
  3148. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  3149. return -EINVAL;
  3150. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  3151. /* Only support XCR0 currently */
  3152. if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
  3153. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  3154. guest_xcrs->xcrs[i].value);
  3155. break;
  3156. }
  3157. if (r)
  3158. r = -EINVAL;
  3159. return r;
  3160. }
  3161. /*
  3162. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  3163. * stopped by the hypervisor. This function will be called from the host only.
  3164. * EINVAL is returned when the host attempts to set the flag for a guest that
  3165. * does not support pv clocks.
  3166. */
  3167. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  3168. {
  3169. if (!vcpu->arch.pv_time_enabled)
  3170. return -EINVAL;
  3171. vcpu->arch.pvclock_set_guest_stopped_request = true;
  3172. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  3173. return 0;
  3174. }
  3175. static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
  3176. struct kvm_enable_cap *cap)
  3177. {
  3178. if (cap->flags)
  3179. return -EINVAL;
  3180. switch (cap->cap) {
  3181. case KVM_CAP_HYPERV_SYNIC2:
  3182. if (cap->args[0])
  3183. return -EINVAL;
  3184. case KVM_CAP_HYPERV_SYNIC:
  3185. if (!irqchip_in_kernel(vcpu->kvm))
  3186. return -EINVAL;
  3187. return kvm_hv_activate_synic(vcpu, cap->cap ==
  3188. KVM_CAP_HYPERV_SYNIC2);
  3189. default:
  3190. return -EINVAL;
  3191. }
  3192. }
  3193. long kvm_arch_vcpu_ioctl(struct file *filp,
  3194. unsigned int ioctl, unsigned long arg)
  3195. {
  3196. struct kvm_vcpu *vcpu = filp->private_data;
  3197. void __user *argp = (void __user *)arg;
  3198. int r;
  3199. union {
  3200. struct kvm_lapic_state *lapic;
  3201. struct kvm_xsave *xsave;
  3202. struct kvm_xcrs *xcrs;
  3203. void *buffer;
  3204. } u;
  3205. vcpu_load(vcpu);
  3206. u.buffer = NULL;
  3207. switch (ioctl) {
  3208. case KVM_GET_LAPIC: {
  3209. r = -EINVAL;
  3210. if (!lapic_in_kernel(vcpu))
  3211. goto out;
  3212. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  3213. r = -ENOMEM;
  3214. if (!u.lapic)
  3215. goto out;
  3216. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  3217. if (r)
  3218. goto out;
  3219. r = -EFAULT;
  3220. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  3221. goto out;
  3222. r = 0;
  3223. break;
  3224. }
  3225. case KVM_SET_LAPIC: {
  3226. r = -EINVAL;
  3227. if (!lapic_in_kernel(vcpu))
  3228. goto out;
  3229. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  3230. if (IS_ERR(u.lapic)) {
  3231. r = PTR_ERR(u.lapic);
  3232. goto out_nofree;
  3233. }
  3234. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  3235. break;
  3236. }
  3237. case KVM_INTERRUPT: {
  3238. struct kvm_interrupt irq;
  3239. r = -EFAULT;
  3240. if (copy_from_user(&irq, argp, sizeof irq))
  3241. goto out;
  3242. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  3243. break;
  3244. }
  3245. case KVM_NMI: {
  3246. r = kvm_vcpu_ioctl_nmi(vcpu);
  3247. break;
  3248. }
  3249. case KVM_SMI: {
  3250. r = kvm_vcpu_ioctl_smi(vcpu);
  3251. break;
  3252. }
  3253. case KVM_SET_CPUID: {
  3254. struct kvm_cpuid __user *cpuid_arg = argp;
  3255. struct kvm_cpuid cpuid;
  3256. r = -EFAULT;
  3257. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3258. goto out;
  3259. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  3260. break;
  3261. }
  3262. case KVM_SET_CPUID2: {
  3263. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3264. struct kvm_cpuid2 cpuid;
  3265. r = -EFAULT;
  3266. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3267. goto out;
  3268. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  3269. cpuid_arg->entries);
  3270. break;
  3271. }
  3272. case KVM_GET_CPUID2: {
  3273. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3274. struct kvm_cpuid2 cpuid;
  3275. r = -EFAULT;
  3276. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3277. goto out;
  3278. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  3279. cpuid_arg->entries);
  3280. if (r)
  3281. goto out;
  3282. r = -EFAULT;
  3283. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  3284. goto out;
  3285. r = 0;
  3286. break;
  3287. }
  3288. case KVM_GET_MSRS: {
  3289. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  3290. r = msr_io(vcpu, argp, do_get_msr, 1);
  3291. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3292. break;
  3293. }
  3294. case KVM_SET_MSRS: {
  3295. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  3296. r = msr_io(vcpu, argp, do_set_msr, 0);
  3297. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3298. break;
  3299. }
  3300. case KVM_TPR_ACCESS_REPORTING: {
  3301. struct kvm_tpr_access_ctl tac;
  3302. r = -EFAULT;
  3303. if (copy_from_user(&tac, argp, sizeof tac))
  3304. goto out;
  3305. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  3306. if (r)
  3307. goto out;
  3308. r = -EFAULT;
  3309. if (copy_to_user(argp, &tac, sizeof tac))
  3310. goto out;
  3311. r = 0;
  3312. break;
  3313. };
  3314. case KVM_SET_VAPIC_ADDR: {
  3315. struct kvm_vapic_addr va;
  3316. int idx;
  3317. r = -EINVAL;
  3318. if (!lapic_in_kernel(vcpu))
  3319. goto out;
  3320. r = -EFAULT;
  3321. if (copy_from_user(&va, argp, sizeof va))
  3322. goto out;
  3323. idx = srcu_read_lock(&vcpu->kvm->srcu);
  3324. r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  3325. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3326. break;
  3327. }
  3328. case KVM_X86_SETUP_MCE: {
  3329. u64 mcg_cap;
  3330. r = -EFAULT;
  3331. if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  3332. goto out;
  3333. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  3334. break;
  3335. }
  3336. case KVM_X86_SET_MCE: {
  3337. struct kvm_x86_mce mce;
  3338. r = -EFAULT;
  3339. if (copy_from_user(&mce, argp, sizeof mce))
  3340. goto out;
  3341. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  3342. break;
  3343. }
  3344. case KVM_GET_VCPU_EVENTS: {
  3345. struct kvm_vcpu_events events;
  3346. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  3347. r = -EFAULT;
  3348. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  3349. break;
  3350. r = 0;
  3351. break;
  3352. }
  3353. case KVM_SET_VCPU_EVENTS: {
  3354. struct kvm_vcpu_events events;
  3355. r = -EFAULT;
  3356. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  3357. break;
  3358. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  3359. break;
  3360. }
  3361. case KVM_GET_DEBUGREGS: {
  3362. struct kvm_debugregs dbgregs;
  3363. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  3364. r = -EFAULT;
  3365. if (copy_to_user(argp, &dbgregs,
  3366. sizeof(struct kvm_debugregs)))
  3367. break;
  3368. r = 0;
  3369. break;
  3370. }
  3371. case KVM_SET_DEBUGREGS: {
  3372. struct kvm_debugregs dbgregs;
  3373. r = -EFAULT;
  3374. if (copy_from_user(&dbgregs, argp,
  3375. sizeof(struct kvm_debugregs)))
  3376. break;
  3377. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  3378. break;
  3379. }
  3380. case KVM_GET_XSAVE: {
  3381. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  3382. r = -ENOMEM;
  3383. if (!u.xsave)
  3384. break;
  3385. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  3386. r = -EFAULT;
  3387. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  3388. break;
  3389. r = 0;
  3390. break;
  3391. }
  3392. case KVM_SET_XSAVE: {
  3393. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  3394. if (IS_ERR(u.xsave)) {
  3395. r = PTR_ERR(u.xsave);
  3396. goto out_nofree;
  3397. }
  3398. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  3399. break;
  3400. }
  3401. case KVM_GET_XCRS: {
  3402. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  3403. r = -ENOMEM;
  3404. if (!u.xcrs)
  3405. break;
  3406. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  3407. r = -EFAULT;
  3408. if (copy_to_user(argp, u.xcrs,
  3409. sizeof(struct kvm_xcrs)))
  3410. break;
  3411. r = 0;
  3412. break;
  3413. }
  3414. case KVM_SET_XCRS: {
  3415. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  3416. if (IS_ERR(u.xcrs)) {
  3417. r = PTR_ERR(u.xcrs);
  3418. goto out_nofree;
  3419. }
  3420. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  3421. break;
  3422. }
  3423. case KVM_SET_TSC_KHZ: {
  3424. u32 user_tsc_khz;
  3425. r = -EINVAL;
  3426. user_tsc_khz = (u32)arg;
  3427. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  3428. goto out;
  3429. if (user_tsc_khz == 0)
  3430. user_tsc_khz = tsc_khz;
  3431. if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
  3432. r = 0;
  3433. goto out;
  3434. }
  3435. case KVM_GET_TSC_KHZ: {
  3436. r = vcpu->arch.virtual_tsc_khz;
  3437. goto out;
  3438. }
  3439. case KVM_KVMCLOCK_CTRL: {
  3440. r = kvm_set_guest_paused(vcpu);
  3441. goto out;
  3442. }
  3443. case KVM_ENABLE_CAP: {
  3444. struct kvm_enable_cap cap;
  3445. r = -EFAULT;
  3446. if (copy_from_user(&cap, argp, sizeof(cap)))
  3447. goto out;
  3448. r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
  3449. break;
  3450. }
  3451. case KVM_GET_NESTED_STATE: {
  3452. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  3453. u32 user_data_size;
  3454. r = -EINVAL;
  3455. if (!kvm_x86_ops->get_nested_state)
  3456. break;
  3457. BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
  3458. if (get_user(user_data_size, &user_kvm_nested_state->size))
  3459. return -EFAULT;
  3460. r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
  3461. user_data_size);
  3462. if (r < 0)
  3463. return r;
  3464. if (r > user_data_size) {
  3465. if (put_user(r, &user_kvm_nested_state->size))
  3466. return -EFAULT;
  3467. return -E2BIG;
  3468. }
  3469. r = 0;
  3470. break;
  3471. }
  3472. case KVM_SET_NESTED_STATE: {
  3473. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  3474. struct kvm_nested_state kvm_state;
  3475. r = -EINVAL;
  3476. if (!kvm_x86_ops->set_nested_state)
  3477. break;
  3478. if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
  3479. return -EFAULT;
  3480. if (kvm_state.size < sizeof(kvm_state))
  3481. return -EINVAL;
  3482. if (kvm_state.flags &
  3483. ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE))
  3484. return -EINVAL;
  3485. /* nested_run_pending implies guest_mode. */
  3486. if (kvm_state.flags == KVM_STATE_NESTED_RUN_PENDING)
  3487. return -EINVAL;
  3488. r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
  3489. break;
  3490. }
  3491. default:
  3492. r = -EINVAL;
  3493. }
  3494. out:
  3495. kfree(u.buffer);
  3496. out_nofree:
  3497. vcpu_put(vcpu);
  3498. return r;
  3499. }
  3500. vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  3501. {
  3502. return VM_FAULT_SIGBUS;
  3503. }
  3504. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  3505. {
  3506. int ret;
  3507. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  3508. return -EINVAL;
  3509. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  3510. return ret;
  3511. }
  3512. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  3513. u64 ident_addr)
  3514. {
  3515. return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
  3516. }
  3517. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  3518. u32 kvm_nr_mmu_pages)
  3519. {
  3520. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  3521. return -EINVAL;
  3522. mutex_lock(&kvm->slots_lock);
  3523. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  3524. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  3525. mutex_unlock(&kvm->slots_lock);
  3526. return 0;
  3527. }
  3528. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  3529. {
  3530. return kvm->arch.n_max_mmu_pages;
  3531. }
  3532. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3533. {
  3534. struct kvm_pic *pic = kvm->arch.vpic;
  3535. int r;
  3536. r = 0;
  3537. switch (chip->chip_id) {
  3538. case KVM_IRQCHIP_PIC_MASTER:
  3539. memcpy(&chip->chip.pic, &pic->pics[0],
  3540. sizeof(struct kvm_pic_state));
  3541. break;
  3542. case KVM_IRQCHIP_PIC_SLAVE:
  3543. memcpy(&chip->chip.pic, &pic->pics[1],
  3544. sizeof(struct kvm_pic_state));
  3545. break;
  3546. case KVM_IRQCHIP_IOAPIC:
  3547. kvm_get_ioapic(kvm, &chip->chip.ioapic);
  3548. break;
  3549. default:
  3550. r = -EINVAL;
  3551. break;
  3552. }
  3553. return r;
  3554. }
  3555. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3556. {
  3557. struct kvm_pic *pic = kvm->arch.vpic;
  3558. int r;
  3559. r = 0;
  3560. switch (chip->chip_id) {
  3561. case KVM_IRQCHIP_PIC_MASTER:
  3562. spin_lock(&pic->lock);
  3563. memcpy(&pic->pics[0], &chip->chip.pic,
  3564. sizeof(struct kvm_pic_state));
  3565. spin_unlock(&pic->lock);
  3566. break;
  3567. case KVM_IRQCHIP_PIC_SLAVE:
  3568. spin_lock(&pic->lock);
  3569. memcpy(&pic->pics[1], &chip->chip.pic,
  3570. sizeof(struct kvm_pic_state));
  3571. spin_unlock(&pic->lock);
  3572. break;
  3573. case KVM_IRQCHIP_IOAPIC:
  3574. kvm_set_ioapic(kvm, &chip->chip.ioapic);
  3575. break;
  3576. default:
  3577. r = -EINVAL;
  3578. break;
  3579. }
  3580. kvm_pic_update_irq(pic);
  3581. return r;
  3582. }
  3583. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3584. {
  3585. struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
  3586. BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
  3587. mutex_lock(&kps->lock);
  3588. memcpy(ps, &kps->channels, sizeof(*ps));
  3589. mutex_unlock(&kps->lock);
  3590. return 0;
  3591. }
  3592. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3593. {
  3594. int i;
  3595. struct kvm_pit *pit = kvm->arch.vpit;
  3596. mutex_lock(&pit->pit_state.lock);
  3597. memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
  3598. for (i = 0; i < 3; i++)
  3599. kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
  3600. mutex_unlock(&pit->pit_state.lock);
  3601. return 0;
  3602. }
  3603. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3604. {
  3605. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  3606. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  3607. sizeof(ps->channels));
  3608. ps->flags = kvm->arch.vpit->pit_state.flags;
  3609. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  3610. memset(&ps->reserved, 0, sizeof(ps->reserved));
  3611. return 0;
  3612. }
  3613. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3614. {
  3615. int start = 0;
  3616. int i;
  3617. u32 prev_legacy, cur_legacy;
  3618. struct kvm_pit *pit = kvm->arch.vpit;
  3619. mutex_lock(&pit->pit_state.lock);
  3620. prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3621. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3622. if (!prev_legacy && cur_legacy)
  3623. start = 1;
  3624. memcpy(&pit->pit_state.channels, &ps->channels,
  3625. sizeof(pit->pit_state.channels));
  3626. pit->pit_state.flags = ps->flags;
  3627. for (i = 0; i < 3; i++)
  3628. kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
  3629. start && i == 0);
  3630. mutex_unlock(&pit->pit_state.lock);
  3631. return 0;
  3632. }
  3633. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  3634. struct kvm_reinject_control *control)
  3635. {
  3636. struct kvm_pit *pit = kvm->arch.vpit;
  3637. if (!pit)
  3638. return -ENXIO;
  3639. /* pit->pit_state.lock was overloaded to prevent userspace from getting
  3640. * an inconsistent state after running multiple KVM_REINJECT_CONTROL
  3641. * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
  3642. */
  3643. mutex_lock(&pit->pit_state.lock);
  3644. kvm_pit_set_reinject(pit, control->pit_reinject);
  3645. mutex_unlock(&pit->pit_state.lock);
  3646. return 0;
  3647. }
  3648. /**
  3649. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  3650. * @kvm: kvm instance
  3651. * @log: slot id and address to which we copy the log
  3652. *
  3653. * Steps 1-4 below provide general overview of dirty page logging. See
  3654. * kvm_get_dirty_log_protect() function description for additional details.
  3655. *
  3656. * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
  3657. * always flush the TLB (step 4) even if previous step failed and the dirty
  3658. * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
  3659. * does not preclude user space subsequent dirty log read. Flushing TLB ensures
  3660. * writes will be marked dirty for next log read.
  3661. *
  3662. * 1. Take a snapshot of the bit and clear it if needed.
  3663. * 2. Write protect the corresponding page.
  3664. * 3. Copy the snapshot to the userspace.
  3665. * 4. Flush TLB's if needed.
  3666. */
  3667. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  3668. {
  3669. bool is_dirty = false;
  3670. int r;
  3671. mutex_lock(&kvm->slots_lock);
  3672. /*
  3673. * Flush potentially hardware-cached dirty pages to dirty_bitmap.
  3674. */
  3675. if (kvm_x86_ops->flush_log_dirty)
  3676. kvm_x86_ops->flush_log_dirty(kvm);
  3677. r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
  3678. /*
  3679. * All the TLBs can be flushed out of mmu lock, see the comments in
  3680. * kvm_mmu_slot_remove_write_access().
  3681. */
  3682. lockdep_assert_held(&kvm->slots_lock);
  3683. if (is_dirty)
  3684. kvm_flush_remote_tlbs(kvm);
  3685. mutex_unlock(&kvm->slots_lock);
  3686. return r;
  3687. }
  3688. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  3689. bool line_status)
  3690. {
  3691. if (!irqchip_in_kernel(kvm))
  3692. return -ENXIO;
  3693. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  3694. irq_event->irq, irq_event->level,
  3695. line_status);
  3696. return 0;
  3697. }
  3698. static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  3699. struct kvm_enable_cap *cap)
  3700. {
  3701. int r;
  3702. if (cap->flags)
  3703. return -EINVAL;
  3704. switch (cap->cap) {
  3705. case KVM_CAP_DISABLE_QUIRKS:
  3706. kvm->arch.disabled_quirks = cap->args[0];
  3707. r = 0;
  3708. break;
  3709. case KVM_CAP_SPLIT_IRQCHIP: {
  3710. mutex_lock(&kvm->lock);
  3711. r = -EINVAL;
  3712. if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
  3713. goto split_irqchip_unlock;
  3714. r = -EEXIST;
  3715. if (irqchip_in_kernel(kvm))
  3716. goto split_irqchip_unlock;
  3717. if (kvm->created_vcpus)
  3718. goto split_irqchip_unlock;
  3719. r = kvm_setup_empty_irq_routing(kvm);
  3720. if (r)
  3721. goto split_irqchip_unlock;
  3722. /* Pairs with irqchip_in_kernel. */
  3723. smp_wmb();
  3724. kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
  3725. kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
  3726. r = 0;
  3727. split_irqchip_unlock:
  3728. mutex_unlock(&kvm->lock);
  3729. break;
  3730. }
  3731. case KVM_CAP_X2APIC_API:
  3732. r = -EINVAL;
  3733. if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
  3734. break;
  3735. if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
  3736. kvm->arch.x2apic_format = true;
  3737. if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  3738. kvm->arch.x2apic_broadcast_quirk_disabled = true;
  3739. r = 0;
  3740. break;
  3741. case KVM_CAP_X86_DISABLE_EXITS:
  3742. r = -EINVAL;
  3743. if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
  3744. break;
  3745. if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
  3746. kvm_can_mwait_in_guest())
  3747. kvm->arch.mwait_in_guest = true;
  3748. if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
  3749. kvm->arch.hlt_in_guest = true;
  3750. if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
  3751. kvm->arch.pause_in_guest = true;
  3752. r = 0;
  3753. break;
  3754. default:
  3755. r = -EINVAL;
  3756. break;
  3757. }
  3758. return r;
  3759. }
  3760. long kvm_arch_vm_ioctl(struct file *filp,
  3761. unsigned int ioctl, unsigned long arg)
  3762. {
  3763. struct kvm *kvm = filp->private_data;
  3764. void __user *argp = (void __user *)arg;
  3765. int r = -ENOTTY;
  3766. /*
  3767. * This union makes it completely explicit to gcc-3.x
  3768. * that these two variables' stack usage should be
  3769. * combined, not added together.
  3770. */
  3771. union {
  3772. struct kvm_pit_state ps;
  3773. struct kvm_pit_state2 ps2;
  3774. struct kvm_pit_config pit_config;
  3775. } u;
  3776. switch (ioctl) {
  3777. case KVM_SET_TSS_ADDR:
  3778. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  3779. break;
  3780. case KVM_SET_IDENTITY_MAP_ADDR: {
  3781. u64 ident_addr;
  3782. mutex_lock(&kvm->lock);
  3783. r = -EINVAL;
  3784. if (kvm->created_vcpus)
  3785. goto set_identity_unlock;
  3786. r = -EFAULT;
  3787. if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  3788. goto set_identity_unlock;
  3789. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  3790. set_identity_unlock:
  3791. mutex_unlock(&kvm->lock);
  3792. break;
  3793. }
  3794. case KVM_SET_NR_MMU_PAGES:
  3795. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  3796. break;
  3797. case KVM_GET_NR_MMU_PAGES:
  3798. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  3799. break;
  3800. case KVM_CREATE_IRQCHIP: {
  3801. mutex_lock(&kvm->lock);
  3802. r = -EEXIST;
  3803. if (irqchip_in_kernel(kvm))
  3804. goto create_irqchip_unlock;
  3805. r = -EINVAL;
  3806. if (kvm->created_vcpus)
  3807. goto create_irqchip_unlock;
  3808. r = kvm_pic_init(kvm);
  3809. if (r)
  3810. goto create_irqchip_unlock;
  3811. r = kvm_ioapic_init(kvm);
  3812. if (r) {
  3813. kvm_pic_destroy(kvm);
  3814. goto create_irqchip_unlock;
  3815. }
  3816. r = kvm_setup_default_irq_routing(kvm);
  3817. if (r) {
  3818. kvm_ioapic_destroy(kvm);
  3819. kvm_pic_destroy(kvm);
  3820. goto create_irqchip_unlock;
  3821. }
  3822. /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
  3823. smp_wmb();
  3824. kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
  3825. create_irqchip_unlock:
  3826. mutex_unlock(&kvm->lock);
  3827. break;
  3828. }
  3829. case KVM_CREATE_PIT:
  3830. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  3831. goto create_pit;
  3832. case KVM_CREATE_PIT2:
  3833. r = -EFAULT;
  3834. if (copy_from_user(&u.pit_config, argp,
  3835. sizeof(struct kvm_pit_config)))
  3836. goto out;
  3837. create_pit:
  3838. mutex_lock(&kvm->lock);
  3839. r = -EEXIST;
  3840. if (kvm->arch.vpit)
  3841. goto create_pit_unlock;
  3842. r = -ENOMEM;
  3843. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  3844. if (kvm->arch.vpit)
  3845. r = 0;
  3846. create_pit_unlock:
  3847. mutex_unlock(&kvm->lock);
  3848. break;
  3849. case KVM_GET_IRQCHIP: {
  3850. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3851. struct kvm_irqchip *chip;
  3852. chip = memdup_user(argp, sizeof(*chip));
  3853. if (IS_ERR(chip)) {
  3854. r = PTR_ERR(chip);
  3855. goto out;
  3856. }
  3857. r = -ENXIO;
  3858. if (!irqchip_kernel(kvm))
  3859. goto get_irqchip_out;
  3860. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  3861. if (r)
  3862. goto get_irqchip_out;
  3863. r = -EFAULT;
  3864. if (copy_to_user(argp, chip, sizeof *chip))
  3865. goto get_irqchip_out;
  3866. r = 0;
  3867. get_irqchip_out:
  3868. kfree(chip);
  3869. break;
  3870. }
  3871. case KVM_SET_IRQCHIP: {
  3872. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3873. struct kvm_irqchip *chip;
  3874. chip = memdup_user(argp, sizeof(*chip));
  3875. if (IS_ERR(chip)) {
  3876. r = PTR_ERR(chip);
  3877. goto out;
  3878. }
  3879. r = -ENXIO;
  3880. if (!irqchip_kernel(kvm))
  3881. goto set_irqchip_out;
  3882. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  3883. if (r)
  3884. goto set_irqchip_out;
  3885. r = 0;
  3886. set_irqchip_out:
  3887. kfree(chip);
  3888. break;
  3889. }
  3890. case KVM_GET_PIT: {
  3891. r = -EFAULT;
  3892. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  3893. goto out;
  3894. r = -ENXIO;
  3895. if (!kvm->arch.vpit)
  3896. goto out;
  3897. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  3898. if (r)
  3899. goto out;
  3900. r = -EFAULT;
  3901. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  3902. goto out;
  3903. r = 0;
  3904. break;
  3905. }
  3906. case KVM_SET_PIT: {
  3907. r = -EFAULT;
  3908. if (copy_from_user(&u.ps, argp, sizeof u.ps))
  3909. goto out;
  3910. r = -ENXIO;
  3911. if (!kvm->arch.vpit)
  3912. goto out;
  3913. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  3914. break;
  3915. }
  3916. case KVM_GET_PIT2: {
  3917. r = -ENXIO;
  3918. if (!kvm->arch.vpit)
  3919. goto out;
  3920. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  3921. if (r)
  3922. goto out;
  3923. r = -EFAULT;
  3924. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  3925. goto out;
  3926. r = 0;
  3927. break;
  3928. }
  3929. case KVM_SET_PIT2: {
  3930. r = -EFAULT;
  3931. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  3932. goto out;
  3933. r = -ENXIO;
  3934. if (!kvm->arch.vpit)
  3935. goto out;
  3936. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  3937. break;
  3938. }
  3939. case KVM_REINJECT_CONTROL: {
  3940. struct kvm_reinject_control control;
  3941. r = -EFAULT;
  3942. if (copy_from_user(&control, argp, sizeof(control)))
  3943. goto out;
  3944. r = kvm_vm_ioctl_reinject(kvm, &control);
  3945. break;
  3946. }
  3947. case KVM_SET_BOOT_CPU_ID:
  3948. r = 0;
  3949. mutex_lock(&kvm->lock);
  3950. if (kvm->created_vcpus)
  3951. r = -EBUSY;
  3952. else
  3953. kvm->arch.bsp_vcpu_id = arg;
  3954. mutex_unlock(&kvm->lock);
  3955. break;
  3956. case KVM_XEN_HVM_CONFIG: {
  3957. struct kvm_xen_hvm_config xhc;
  3958. r = -EFAULT;
  3959. if (copy_from_user(&xhc, argp, sizeof(xhc)))
  3960. goto out;
  3961. r = -EINVAL;
  3962. if (xhc.flags)
  3963. goto out;
  3964. memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
  3965. r = 0;
  3966. break;
  3967. }
  3968. case KVM_SET_CLOCK: {
  3969. struct kvm_clock_data user_ns;
  3970. u64 now_ns;
  3971. r = -EFAULT;
  3972. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  3973. goto out;
  3974. r = -EINVAL;
  3975. if (user_ns.flags)
  3976. goto out;
  3977. r = 0;
  3978. /*
  3979. * TODO: userspace has to take care of races with VCPU_RUN, so
  3980. * kvm_gen_update_masterclock() can be cut down to locked
  3981. * pvclock_update_vm_gtod_copy().
  3982. */
  3983. kvm_gen_update_masterclock(kvm);
  3984. now_ns = get_kvmclock_ns(kvm);
  3985. kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
  3986. kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
  3987. break;
  3988. }
  3989. case KVM_GET_CLOCK: {
  3990. struct kvm_clock_data user_ns;
  3991. u64 now_ns;
  3992. now_ns = get_kvmclock_ns(kvm);
  3993. user_ns.clock = now_ns;
  3994. user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
  3995. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  3996. r = -EFAULT;
  3997. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  3998. goto out;
  3999. r = 0;
  4000. break;
  4001. }
  4002. case KVM_ENABLE_CAP: {
  4003. struct kvm_enable_cap cap;
  4004. r = -EFAULT;
  4005. if (copy_from_user(&cap, argp, sizeof(cap)))
  4006. goto out;
  4007. r = kvm_vm_ioctl_enable_cap(kvm, &cap);
  4008. break;
  4009. }
  4010. case KVM_MEMORY_ENCRYPT_OP: {
  4011. r = -ENOTTY;
  4012. if (kvm_x86_ops->mem_enc_op)
  4013. r = kvm_x86_ops->mem_enc_op(kvm, argp);
  4014. break;
  4015. }
  4016. case KVM_MEMORY_ENCRYPT_REG_REGION: {
  4017. struct kvm_enc_region region;
  4018. r = -EFAULT;
  4019. if (copy_from_user(&region, argp, sizeof(region)))
  4020. goto out;
  4021. r = -ENOTTY;
  4022. if (kvm_x86_ops->mem_enc_reg_region)
  4023. r = kvm_x86_ops->mem_enc_reg_region(kvm, &region);
  4024. break;
  4025. }
  4026. case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
  4027. struct kvm_enc_region region;
  4028. r = -EFAULT;
  4029. if (copy_from_user(&region, argp, sizeof(region)))
  4030. goto out;
  4031. r = -ENOTTY;
  4032. if (kvm_x86_ops->mem_enc_unreg_region)
  4033. r = kvm_x86_ops->mem_enc_unreg_region(kvm, &region);
  4034. break;
  4035. }
  4036. case KVM_HYPERV_EVENTFD: {
  4037. struct kvm_hyperv_eventfd hvevfd;
  4038. r = -EFAULT;
  4039. if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
  4040. goto out;
  4041. r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
  4042. break;
  4043. }
  4044. default:
  4045. r = -ENOTTY;
  4046. }
  4047. out:
  4048. return r;
  4049. }
  4050. static void kvm_init_msr_list(void)
  4051. {
  4052. u32 dummy[2];
  4053. unsigned i, j;
  4054. for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
  4055. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  4056. continue;
  4057. /*
  4058. * Even MSRs that are valid in the host may not be exposed
  4059. * to the guests in some cases.
  4060. */
  4061. switch (msrs_to_save[i]) {
  4062. case MSR_IA32_BNDCFGS:
  4063. if (!kvm_x86_ops->mpx_supported())
  4064. continue;
  4065. break;
  4066. case MSR_TSC_AUX:
  4067. if (!kvm_x86_ops->rdtscp_supported())
  4068. continue;
  4069. break;
  4070. default:
  4071. break;
  4072. }
  4073. if (j < i)
  4074. msrs_to_save[j] = msrs_to_save[i];
  4075. j++;
  4076. }
  4077. num_msrs_to_save = j;
  4078. for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
  4079. if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
  4080. continue;
  4081. if (j < i)
  4082. emulated_msrs[j] = emulated_msrs[i];
  4083. j++;
  4084. }
  4085. num_emulated_msrs = j;
  4086. for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
  4087. struct kvm_msr_entry msr;
  4088. msr.index = msr_based_features[i];
  4089. if (kvm_get_msr_feature(&msr))
  4090. continue;
  4091. if (j < i)
  4092. msr_based_features[j] = msr_based_features[i];
  4093. j++;
  4094. }
  4095. num_msr_based_features = j;
  4096. }
  4097. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  4098. const void *v)
  4099. {
  4100. int handled = 0;
  4101. int n;
  4102. do {
  4103. n = min(len, 8);
  4104. if (!(lapic_in_kernel(vcpu) &&
  4105. !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
  4106. && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
  4107. break;
  4108. handled += n;
  4109. addr += n;
  4110. len -= n;
  4111. v += n;
  4112. } while (len);
  4113. return handled;
  4114. }
  4115. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  4116. {
  4117. int handled = 0;
  4118. int n;
  4119. do {
  4120. n = min(len, 8);
  4121. if (!(lapic_in_kernel(vcpu) &&
  4122. !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
  4123. addr, n, v))
  4124. && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
  4125. break;
  4126. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
  4127. handled += n;
  4128. addr += n;
  4129. len -= n;
  4130. v += n;
  4131. } while (len);
  4132. return handled;
  4133. }
  4134. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  4135. struct kvm_segment *var, int seg)
  4136. {
  4137. kvm_x86_ops->set_segment(vcpu, var, seg);
  4138. }
  4139. void kvm_get_segment(struct kvm_vcpu *vcpu,
  4140. struct kvm_segment *var, int seg)
  4141. {
  4142. kvm_x86_ops->get_segment(vcpu, var, seg);
  4143. }
  4144. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
  4145. struct x86_exception *exception)
  4146. {
  4147. gpa_t t_gpa;
  4148. BUG_ON(!mmu_is_nested(vcpu));
  4149. /* NPT walks are always user-walks */
  4150. access |= PFERR_USER_MASK;
  4151. t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
  4152. return t_gpa;
  4153. }
  4154. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  4155. struct x86_exception *exception)
  4156. {
  4157. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4158. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4159. }
  4160. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  4161. struct x86_exception *exception)
  4162. {
  4163. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4164. access |= PFERR_FETCH_MASK;
  4165. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4166. }
  4167. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  4168. struct x86_exception *exception)
  4169. {
  4170. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4171. access |= PFERR_WRITE_MASK;
  4172. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4173. }
  4174. /* uses this to access any guest's mapped memory without checking CPL */
  4175. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  4176. struct x86_exception *exception)
  4177. {
  4178. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  4179. }
  4180. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  4181. struct kvm_vcpu *vcpu, u32 access,
  4182. struct x86_exception *exception)
  4183. {
  4184. void *data = val;
  4185. int r = X86EMUL_CONTINUE;
  4186. while (bytes) {
  4187. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  4188. exception);
  4189. unsigned offset = addr & (PAGE_SIZE-1);
  4190. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  4191. int ret;
  4192. if (gpa == UNMAPPED_GVA)
  4193. return X86EMUL_PROPAGATE_FAULT;
  4194. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
  4195. offset, toread);
  4196. if (ret < 0) {
  4197. r = X86EMUL_IO_NEEDED;
  4198. goto out;
  4199. }
  4200. bytes -= toread;
  4201. data += toread;
  4202. addr += toread;
  4203. }
  4204. out:
  4205. return r;
  4206. }
  4207. /* used for instruction fetching */
  4208. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  4209. gva_t addr, void *val, unsigned int bytes,
  4210. struct x86_exception *exception)
  4211. {
  4212. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4213. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4214. unsigned offset;
  4215. int ret;
  4216. /* Inline kvm_read_guest_virt_helper for speed. */
  4217. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
  4218. exception);
  4219. if (unlikely(gpa == UNMAPPED_GVA))
  4220. return X86EMUL_PROPAGATE_FAULT;
  4221. offset = addr & (PAGE_SIZE-1);
  4222. if (WARN_ON(offset + bytes > PAGE_SIZE))
  4223. bytes = (unsigned)PAGE_SIZE - offset;
  4224. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
  4225. offset, bytes);
  4226. if (unlikely(ret < 0))
  4227. return X86EMUL_IO_NEEDED;
  4228. return X86EMUL_CONTINUE;
  4229. }
  4230. int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
  4231. gva_t addr, void *val, unsigned int bytes,
  4232. struct x86_exception *exception)
  4233. {
  4234. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4235. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  4236. exception);
  4237. }
  4238. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  4239. static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
  4240. gva_t addr, void *val, unsigned int bytes,
  4241. struct x86_exception *exception, bool system)
  4242. {
  4243. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4244. u32 access = 0;
  4245. if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
  4246. access |= PFERR_USER_MASK;
  4247. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
  4248. }
  4249. static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
  4250. unsigned long addr, void *val, unsigned int bytes)
  4251. {
  4252. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4253. int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
  4254. return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
  4255. }
  4256. static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  4257. struct kvm_vcpu *vcpu, u32 access,
  4258. struct x86_exception *exception)
  4259. {
  4260. void *data = val;
  4261. int r = X86EMUL_CONTINUE;
  4262. while (bytes) {
  4263. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  4264. access,
  4265. exception);
  4266. unsigned offset = addr & (PAGE_SIZE-1);
  4267. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  4268. int ret;
  4269. if (gpa == UNMAPPED_GVA)
  4270. return X86EMUL_PROPAGATE_FAULT;
  4271. ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
  4272. if (ret < 0) {
  4273. r = X86EMUL_IO_NEEDED;
  4274. goto out;
  4275. }
  4276. bytes -= towrite;
  4277. data += towrite;
  4278. addr += towrite;
  4279. }
  4280. out:
  4281. return r;
  4282. }
  4283. static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
  4284. unsigned int bytes, struct x86_exception *exception,
  4285. bool system)
  4286. {
  4287. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4288. u32 access = PFERR_WRITE_MASK;
  4289. if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
  4290. access |= PFERR_USER_MASK;
  4291. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  4292. access, exception);
  4293. }
  4294. int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
  4295. unsigned int bytes, struct x86_exception *exception)
  4296. {
  4297. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  4298. PFERR_WRITE_MASK, exception);
  4299. }
  4300. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  4301. int handle_ud(struct kvm_vcpu *vcpu)
  4302. {
  4303. int emul_type = EMULTYPE_TRAP_UD;
  4304. enum emulation_result er;
  4305. char sig[5]; /* ud2; .ascii "kvm" */
  4306. struct x86_exception e;
  4307. if (force_emulation_prefix &&
  4308. kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
  4309. sig, sizeof(sig), &e) == 0 &&
  4310. memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
  4311. kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
  4312. emul_type = 0;
  4313. }
  4314. er = emulate_instruction(vcpu, emul_type);
  4315. if (er == EMULATE_USER_EXIT)
  4316. return 0;
  4317. if (er != EMULATE_DONE)
  4318. kvm_queue_exception(vcpu, UD_VECTOR);
  4319. return 1;
  4320. }
  4321. EXPORT_SYMBOL_GPL(handle_ud);
  4322. static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  4323. gpa_t gpa, bool write)
  4324. {
  4325. /* For APIC access vmexit */
  4326. if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  4327. return 1;
  4328. if (vcpu_match_mmio_gpa(vcpu, gpa)) {
  4329. trace_vcpu_match_mmio(gva, gpa, write, true);
  4330. return 1;
  4331. }
  4332. return 0;
  4333. }
  4334. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  4335. gpa_t *gpa, struct x86_exception *exception,
  4336. bool write)
  4337. {
  4338. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  4339. | (write ? PFERR_WRITE_MASK : 0);
  4340. /*
  4341. * currently PKRU is only applied to ept enabled guest so
  4342. * there is no pkey in EPT page table for L1 guest or EPT
  4343. * shadow page table for L2 guest.
  4344. */
  4345. if (vcpu_match_mmio_gva(vcpu, gva)
  4346. && !permission_fault(vcpu, vcpu->arch.walk_mmu,
  4347. vcpu->arch.access, 0, access)) {
  4348. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  4349. (gva & (PAGE_SIZE - 1));
  4350. trace_vcpu_match_mmio(gva, *gpa, write, false);
  4351. return 1;
  4352. }
  4353. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4354. if (*gpa == UNMAPPED_GVA)
  4355. return -1;
  4356. return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
  4357. }
  4358. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  4359. const void *val, int bytes)
  4360. {
  4361. int ret;
  4362. ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
  4363. if (ret < 0)
  4364. return 0;
  4365. kvm_page_track_write(vcpu, gpa, val, bytes);
  4366. return 1;
  4367. }
  4368. struct read_write_emulator_ops {
  4369. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  4370. int bytes);
  4371. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4372. void *val, int bytes);
  4373. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4374. int bytes, void *val);
  4375. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4376. void *val, int bytes);
  4377. bool write;
  4378. };
  4379. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  4380. {
  4381. if (vcpu->mmio_read_completed) {
  4382. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  4383. vcpu->mmio_fragments[0].gpa, val);
  4384. vcpu->mmio_read_completed = 0;
  4385. return 1;
  4386. }
  4387. return 0;
  4388. }
  4389. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  4390. void *val, int bytes)
  4391. {
  4392. return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
  4393. }
  4394. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  4395. void *val, int bytes)
  4396. {
  4397. return emulator_write_phys(vcpu, gpa, val, bytes);
  4398. }
  4399. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  4400. {
  4401. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
  4402. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  4403. }
  4404. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  4405. void *val, int bytes)
  4406. {
  4407. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
  4408. return X86EMUL_IO_NEEDED;
  4409. }
  4410. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  4411. void *val, int bytes)
  4412. {
  4413. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  4414. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  4415. return X86EMUL_CONTINUE;
  4416. }
  4417. static const struct read_write_emulator_ops read_emultor = {
  4418. .read_write_prepare = read_prepare,
  4419. .read_write_emulate = read_emulate,
  4420. .read_write_mmio = vcpu_mmio_read,
  4421. .read_write_exit_mmio = read_exit_mmio,
  4422. };
  4423. static const struct read_write_emulator_ops write_emultor = {
  4424. .read_write_emulate = write_emulate,
  4425. .read_write_mmio = write_mmio,
  4426. .read_write_exit_mmio = write_exit_mmio,
  4427. .write = true,
  4428. };
  4429. static int emulator_read_write_onepage(unsigned long addr, void *val,
  4430. unsigned int bytes,
  4431. struct x86_exception *exception,
  4432. struct kvm_vcpu *vcpu,
  4433. const struct read_write_emulator_ops *ops)
  4434. {
  4435. gpa_t gpa;
  4436. int handled, ret;
  4437. bool write = ops->write;
  4438. struct kvm_mmio_fragment *frag;
  4439. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4440. /*
  4441. * If the exit was due to a NPF we may already have a GPA.
  4442. * If the GPA is present, use it to avoid the GVA to GPA table walk.
  4443. * Note, this cannot be used on string operations since string
  4444. * operation using rep will only have the initial GPA from the NPF
  4445. * occurred.
  4446. */
  4447. if (vcpu->arch.gpa_available &&
  4448. emulator_can_use_gpa(ctxt) &&
  4449. (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
  4450. gpa = vcpu->arch.gpa_val;
  4451. ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
  4452. } else {
  4453. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  4454. if (ret < 0)
  4455. return X86EMUL_PROPAGATE_FAULT;
  4456. }
  4457. if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
  4458. return X86EMUL_CONTINUE;
  4459. /*
  4460. * Is this MMIO handled locally?
  4461. */
  4462. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  4463. if (handled == bytes)
  4464. return X86EMUL_CONTINUE;
  4465. gpa += handled;
  4466. bytes -= handled;
  4467. val += handled;
  4468. WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
  4469. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  4470. frag->gpa = gpa;
  4471. frag->data = val;
  4472. frag->len = bytes;
  4473. return X86EMUL_CONTINUE;
  4474. }
  4475. static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
  4476. unsigned long addr,
  4477. void *val, unsigned int bytes,
  4478. struct x86_exception *exception,
  4479. const struct read_write_emulator_ops *ops)
  4480. {
  4481. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4482. gpa_t gpa;
  4483. int rc;
  4484. if (ops->read_write_prepare &&
  4485. ops->read_write_prepare(vcpu, val, bytes))
  4486. return X86EMUL_CONTINUE;
  4487. vcpu->mmio_nr_fragments = 0;
  4488. /* Crossing a page boundary? */
  4489. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  4490. int now;
  4491. now = -addr & ~PAGE_MASK;
  4492. rc = emulator_read_write_onepage(addr, val, now, exception,
  4493. vcpu, ops);
  4494. if (rc != X86EMUL_CONTINUE)
  4495. return rc;
  4496. addr += now;
  4497. if (ctxt->mode != X86EMUL_MODE_PROT64)
  4498. addr = (u32)addr;
  4499. val += now;
  4500. bytes -= now;
  4501. }
  4502. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  4503. vcpu, ops);
  4504. if (rc != X86EMUL_CONTINUE)
  4505. return rc;
  4506. if (!vcpu->mmio_nr_fragments)
  4507. return rc;
  4508. gpa = vcpu->mmio_fragments[0].gpa;
  4509. vcpu->mmio_needed = 1;
  4510. vcpu->mmio_cur_fragment = 0;
  4511. vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
  4512. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  4513. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  4514. vcpu->run->mmio.phys_addr = gpa;
  4515. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  4516. }
  4517. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  4518. unsigned long addr,
  4519. void *val,
  4520. unsigned int bytes,
  4521. struct x86_exception *exception)
  4522. {
  4523. return emulator_read_write(ctxt, addr, val, bytes,
  4524. exception, &read_emultor);
  4525. }
  4526. static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  4527. unsigned long addr,
  4528. const void *val,
  4529. unsigned int bytes,
  4530. struct x86_exception *exception)
  4531. {
  4532. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  4533. exception, &write_emultor);
  4534. }
  4535. #define CMPXCHG_TYPE(t, ptr, old, new) \
  4536. (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  4537. #ifdef CONFIG_X86_64
  4538. # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  4539. #else
  4540. # define CMPXCHG64(ptr, old, new) \
  4541. (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
  4542. #endif
  4543. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  4544. unsigned long addr,
  4545. const void *old,
  4546. const void *new,
  4547. unsigned int bytes,
  4548. struct x86_exception *exception)
  4549. {
  4550. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4551. gpa_t gpa;
  4552. struct page *page;
  4553. char *kaddr;
  4554. bool exchanged;
  4555. /* guests cmpxchg8b have to be emulated atomically */
  4556. if (bytes > 8 || (bytes & (bytes - 1)))
  4557. goto emul_write;
  4558. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  4559. if (gpa == UNMAPPED_GVA ||
  4560. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  4561. goto emul_write;
  4562. if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  4563. goto emul_write;
  4564. page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
  4565. if (is_error_page(page))
  4566. goto emul_write;
  4567. kaddr = kmap_atomic(page);
  4568. kaddr += offset_in_page(gpa);
  4569. switch (bytes) {
  4570. case 1:
  4571. exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  4572. break;
  4573. case 2:
  4574. exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  4575. break;
  4576. case 4:
  4577. exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  4578. break;
  4579. case 8:
  4580. exchanged = CMPXCHG64(kaddr, old, new);
  4581. break;
  4582. default:
  4583. BUG();
  4584. }
  4585. kunmap_atomic(kaddr);
  4586. kvm_release_page_dirty(page);
  4587. if (!exchanged)
  4588. return X86EMUL_CMPXCHG_FAILED;
  4589. kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
  4590. kvm_page_track_write(vcpu, gpa, new, bytes);
  4591. return X86EMUL_CONTINUE;
  4592. emul_write:
  4593. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  4594. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  4595. }
  4596. static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  4597. {
  4598. int r = 0, i;
  4599. for (i = 0; i < vcpu->arch.pio.count; i++) {
  4600. if (vcpu->arch.pio.in)
  4601. r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
  4602. vcpu->arch.pio.size, pd);
  4603. else
  4604. r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
  4605. vcpu->arch.pio.port, vcpu->arch.pio.size,
  4606. pd);
  4607. if (r)
  4608. break;
  4609. pd += vcpu->arch.pio.size;
  4610. }
  4611. return r;
  4612. }
  4613. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  4614. unsigned short port, void *val,
  4615. unsigned int count, bool in)
  4616. {
  4617. vcpu->arch.pio.port = port;
  4618. vcpu->arch.pio.in = in;
  4619. vcpu->arch.pio.count = count;
  4620. vcpu->arch.pio.size = size;
  4621. if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
  4622. vcpu->arch.pio.count = 0;
  4623. return 1;
  4624. }
  4625. vcpu->run->exit_reason = KVM_EXIT_IO;
  4626. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  4627. vcpu->run->io.size = size;
  4628. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  4629. vcpu->run->io.count = count;
  4630. vcpu->run->io.port = port;
  4631. return 0;
  4632. }
  4633. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  4634. int size, unsigned short port, void *val,
  4635. unsigned int count)
  4636. {
  4637. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4638. int ret;
  4639. if (vcpu->arch.pio.count)
  4640. goto data_avail;
  4641. memset(vcpu->arch.pio_data, 0, size * count);
  4642. ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  4643. if (ret) {
  4644. data_avail:
  4645. memcpy(val, vcpu->arch.pio_data, size * count);
  4646. trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
  4647. vcpu->arch.pio.count = 0;
  4648. return 1;
  4649. }
  4650. return 0;
  4651. }
  4652. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  4653. int size, unsigned short port,
  4654. const void *val, unsigned int count)
  4655. {
  4656. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4657. memcpy(vcpu->arch.pio_data, val, size * count);
  4658. trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
  4659. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  4660. }
  4661. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  4662. {
  4663. return kvm_x86_ops->get_segment_base(vcpu, seg);
  4664. }
  4665. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  4666. {
  4667. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  4668. }
  4669. static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
  4670. {
  4671. if (!need_emulate_wbinvd(vcpu))
  4672. return X86EMUL_CONTINUE;
  4673. if (kvm_x86_ops->has_wbinvd_exit()) {
  4674. int cpu = get_cpu();
  4675. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  4676. smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  4677. wbinvd_ipi, NULL, 1);
  4678. put_cpu();
  4679. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  4680. } else
  4681. wbinvd();
  4682. return X86EMUL_CONTINUE;
  4683. }
  4684. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  4685. {
  4686. kvm_emulate_wbinvd_noskip(vcpu);
  4687. return kvm_skip_emulated_instruction(vcpu);
  4688. }
  4689. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  4690. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  4691. {
  4692. kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
  4693. }
  4694. static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4695. unsigned long *dest)
  4696. {
  4697. return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  4698. }
  4699. static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4700. unsigned long value)
  4701. {
  4702. return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  4703. }
  4704. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  4705. {
  4706. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  4707. }
  4708. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  4709. {
  4710. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4711. unsigned long value;
  4712. switch (cr) {
  4713. case 0:
  4714. value = kvm_read_cr0(vcpu);
  4715. break;
  4716. case 2:
  4717. value = vcpu->arch.cr2;
  4718. break;
  4719. case 3:
  4720. value = kvm_read_cr3(vcpu);
  4721. break;
  4722. case 4:
  4723. value = kvm_read_cr4(vcpu);
  4724. break;
  4725. case 8:
  4726. value = kvm_get_cr8(vcpu);
  4727. break;
  4728. default:
  4729. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4730. return 0;
  4731. }
  4732. return value;
  4733. }
  4734. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  4735. {
  4736. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4737. int res = 0;
  4738. switch (cr) {
  4739. case 0:
  4740. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  4741. break;
  4742. case 2:
  4743. vcpu->arch.cr2 = val;
  4744. break;
  4745. case 3:
  4746. res = kvm_set_cr3(vcpu, val);
  4747. break;
  4748. case 4:
  4749. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  4750. break;
  4751. case 8:
  4752. res = kvm_set_cr8(vcpu, val);
  4753. break;
  4754. default:
  4755. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4756. res = -1;
  4757. }
  4758. return res;
  4759. }
  4760. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  4761. {
  4762. return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
  4763. }
  4764. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4765. {
  4766. kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
  4767. }
  4768. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4769. {
  4770. kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
  4771. }
  4772. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4773. {
  4774. kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  4775. }
  4776. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4777. {
  4778. kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  4779. }
  4780. static unsigned long emulator_get_cached_segment_base(
  4781. struct x86_emulate_ctxt *ctxt, int seg)
  4782. {
  4783. return get_segment_base(emul_to_vcpu(ctxt), seg);
  4784. }
  4785. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  4786. struct desc_struct *desc, u32 *base3,
  4787. int seg)
  4788. {
  4789. struct kvm_segment var;
  4790. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  4791. *selector = var.selector;
  4792. if (var.unusable) {
  4793. memset(desc, 0, sizeof(*desc));
  4794. if (base3)
  4795. *base3 = 0;
  4796. return false;
  4797. }
  4798. if (var.g)
  4799. var.limit >>= 12;
  4800. set_desc_limit(desc, var.limit);
  4801. set_desc_base(desc, (unsigned long)var.base);
  4802. #ifdef CONFIG_X86_64
  4803. if (base3)
  4804. *base3 = var.base >> 32;
  4805. #endif
  4806. desc->type = var.type;
  4807. desc->s = var.s;
  4808. desc->dpl = var.dpl;
  4809. desc->p = var.present;
  4810. desc->avl = var.avl;
  4811. desc->l = var.l;
  4812. desc->d = var.db;
  4813. desc->g = var.g;
  4814. return true;
  4815. }
  4816. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  4817. struct desc_struct *desc, u32 base3,
  4818. int seg)
  4819. {
  4820. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4821. struct kvm_segment var;
  4822. var.selector = selector;
  4823. var.base = get_desc_base(desc);
  4824. #ifdef CONFIG_X86_64
  4825. var.base |= ((u64)base3) << 32;
  4826. #endif
  4827. var.limit = get_desc_limit(desc);
  4828. if (desc->g)
  4829. var.limit = (var.limit << 12) | 0xfff;
  4830. var.type = desc->type;
  4831. var.dpl = desc->dpl;
  4832. var.db = desc->d;
  4833. var.s = desc->s;
  4834. var.l = desc->l;
  4835. var.g = desc->g;
  4836. var.avl = desc->avl;
  4837. var.present = desc->p;
  4838. var.unusable = !var.present;
  4839. var.padding = 0;
  4840. kvm_set_segment(vcpu, &var, seg);
  4841. return;
  4842. }
  4843. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  4844. u32 msr_index, u64 *pdata)
  4845. {
  4846. struct msr_data msr;
  4847. int r;
  4848. msr.index = msr_index;
  4849. msr.host_initiated = false;
  4850. r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
  4851. if (r)
  4852. return r;
  4853. *pdata = msr.data;
  4854. return 0;
  4855. }
  4856. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  4857. u32 msr_index, u64 data)
  4858. {
  4859. struct msr_data msr;
  4860. msr.data = data;
  4861. msr.index = msr_index;
  4862. msr.host_initiated = false;
  4863. return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
  4864. }
  4865. static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
  4866. {
  4867. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4868. return vcpu->arch.smbase;
  4869. }
  4870. static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
  4871. {
  4872. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4873. vcpu->arch.smbase = smbase;
  4874. }
  4875. static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
  4876. u32 pmc)
  4877. {
  4878. return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
  4879. }
  4880. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  4881. u32 pmc, u64 *pdata)
  4882. {
  4883. return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
  4884. }
  4885. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  4886. {
  4887. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  4888. }
  4889. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  4890. struct x86_instruction_info *info,
  4891. enum x86_intercept_stage stage)
  4892. {
  4893. return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
  4894. }
  4895. static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  4896. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
  4897. {
  4898. return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
  4899. }
  4900. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  4901. {
  4902. return kvm_register_read(emul_to_vcpu(ctxt), reg);
  4903. }
  4904. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  4905. {
  4906. kvm_register_write(emul_to_vcpu(ctxt), reg, val);
  4907. }
  4908. static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
  4909. {
  4910. kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
  4911. }
  4912. static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
  4913. {
  4914. return emul_to_vcpu(ctxt)->arch.hflags;
  4915. }
  4916. static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
  4917. {
  4918. kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
  4919. }
  4920. static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
  4921. {
  4922. return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
  4923. }
  4924. static const struct x86_emulate_ops emulate_ops = {
  4925. .read_gpr = emulator_read_gpr,
  4926. .write_gpr = emulator_write_gpr,
  4927. .read_std = emulator_read_std,
  4928. .write_std = emulator_write_std,
  4929. .read_phys = kvm_read_guest_phys_system,
  4930. .fetch = kvm_fetch_guest_virt,
  4931. .read_emulated = emulator_read_emulated,
  4932. .write_emulated = emulator_write_emulated,
  4933. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  4934. .invlpg = emulator_invlpg,
  4935. .pio_in_emulated = emulator_pio_in_emulated,
  4936. .pio_out_emulated = emulator_pio_out_emulated,
  4937. .get_segment = emulator_get_segment,
  4938. .set_segment = emulator_set_segment,
  4939. .get_cached_segment_base = emulator_get_cached_segment_base,
  4940. .get_gdt = emulator_get_gdt,
  4941. .get_idt = emulator_get_idt,
  4942. .set_gdt = emulator_set_gdt,
  4943. .set_idt = emulator_set_idt,
  4944. .get_cr = emulator_get_cr,
  4945. .set_cr = emulator_set_cr,
  4946. .cpl = emulator_get_cpl,
  4947. .get_dr = emulator_get_dr,
  4948. .set_dr = emulator_set_dr,
  4949. .get_smbase = emulator_get_smbase,
  4950. .set_smbase = emulator_set_smbase,
  4951. .set_msr = emulator_set_msr,
  4952. .get_msr = emulator_get_msr,
  4953. .check_pmc = emulator_check_pmc,
  4954. .read_pmc = emulator_read_pmc,
  4955. .halt = emulator_halt,
  4956. .wbinvd = emulator_wbinvd,
  4957. .fix_hypercall = emulator_fix_hypercall,
  4958. .intercept = emulator_intercept,
  4959. .get_cpuid = emulator_get_cpuid,
  4960. .set_nmi_mask = emulator_set_nmi_mask,
  4961. .get_hflags = emulator_get_hflags,
  4962. .set_hflags = emulator_set_hflags,
  4963. .pre_leave_smm = emulator_pre_leave_smm,
  4964. };
  4965. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  4966. {
  4967. u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  4968. /*
  4969. * an sti; sti; sequence only disable interrupts for the first
  4970. * instruction. So, if the last instruction, be it emulated or
  4971. * not, left the system with the INT_STI flag enabled, it
  4972. * means that the last instruction is an sti. We should not
  4973. * leave the flag on in this case. The same goes for mov ss
  4974. */
  4975. if (int_shadow & mask)
  4976. mask = 0;
  4977. if (unlikely(int_shadow || mask)) {
  4978. kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  4979. if (!mask)
  4980. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4981. }
  4982. }
  4983. static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
  4984. {
  4985. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4986. if (ctxt->exception.vector == PF_VECTOR)
  4987. return kvm_propagate_fault(vcpu, &ctxt->exception);
  4988. if (ctxt->exception.error_code_valid)
  4989. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  4990. ctxt->exception.error_code);
  4991. else
  4992. kvm_queue_exception(vcpu, ctxt->exception.vector);
  4993. return false;
  4994. }
  4995. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  4996. {
  4997. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4998. int cs_db, cs_l;
  4999. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  5000. ctxt->eflags = kvm_get_rflags(vcpu);
  5001. ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
  5002. ctxt->eip = kvm_rip_read(vcpu);
  5003. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  5004. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  5005. (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
  5006. cs_db ? X86EMUL_MODE_PROT32 :
  5007. X86EMUL_MODE_PROT16;
  5008. BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
  5009. BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
  5010. BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
  5011. init_decode_cache(ctxt);
  5012. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  5013. }
  5014. int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  5015. {
  5016. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5017. int ret;
  5018. init_emulate_ctxt(vcpu);
  5019. ctxt->op_bytes = 2;
  5020. ctxt->ad_bytes = 2;
  5021. ctxt->_eip = ctxt->eip + inc_eip;
  5022. ret = emulate_int_real(ctxt, irq);
  5023. if (ret != X86EMUL_CONTINUE)
  5024. return EMULATE_FAIL;
  5025. ctxt->eip = ctxt->_eip;
  5026. kvm_rip_write(vcpu, ctxt->eip);
  5027. kvm_set_rflags(vcpu, ctxt->eflags);
  5028. return EMULATE_DONE;
  5029. }
  5030. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  5031. static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
  5032. {
  5033. int r = EMULATE_DONE;
  5034. ++vcpu->stat.insn_emulation_fail;
  5035. trace_kvm_emulate_insn_failed(vcpu);
  5036. if (emulation_type & EMULTYPE_NO_UD_ON_FAIL)
  5037. return EMULATE_FAIL;
  5038. if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
  5039. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  5040. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  5041. vcpu->run->internal.ndata = 0;
  5042. r = EMULATE_USER_EXIT;
  5043. }
  5044. kvm_queue_exception(vcpu, UD_VECTOR);
  5045. return r;
  5046. }
  5047. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
  5048. bool write_fault_to_shadow_pgtable,
  5049. int emulation_type)
  5050. {
  5051. gpa_t gpa = cr2;
  5052. kvm_pfn_t pfn;
  5053. if (emulation_type & EMULTYPE_NO_REEXECUTE)
  5054. return false;
  5055. if (!vcpu->arch.mmu.direct_map) {
  5056. /*
  5057. * Write permission should be allowed since only
  5058. * write access need to be emulated.
  5059. */
  5060. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  5061. /*
  5062. * If the mapping is invalid in guest, let cpu retry
  5063. * it to generate fault.
  5064. */
  5065. if (gpa == UNMAPPED_GVA)
  5066. return true;
  5067. }
  5068. /*
  5069. * Do not retry the unhandleable instruction if it faults on the
  5070. * readonly host memory, otherwise it will goto a infinite loop:
  5071. * retry instruction -> write #PF -> emulation fail -> retry
  5072. * instruction -> ...
  5073. */
  5074. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  5075. /*
  5076. * If the instruction failed on the error pfn, it can not be fixed,
  5077. * report the error to userspace.
  5078. */
  5079. if (is_error_noslot_pfn(pfn))
  5080. return false;
  5081. kvm_release_pfn_clean(pfn);
  5082. /* The instructions are well-emulated on direct mmu. */
  5083. if (vcpu->arch.mmu.direct_map) {
  5084. unsigned int indirect_shadow_pages;
  5085. spin_lock(&vcpu->kvm->mmu_lock);
  5086. indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
  5087. spin_unlock(&vcpu->kvm->mmu_lock);
  5088. if (indirect_shadow_pages)
  5089. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5090. return true;
  5091. }
  5092. /*
  5093. * if emulation was due to access to shadowed page table
  5094. * and it failed try to unshadow page and re-enter the
  5095. * guest to let CPU execute the instruction.
  5096. */
  5097. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5098. /*
  5099. * If the access faults on its page table, it can not
  5100. * be fixed by unprotecting shadow page and it should
  5101. * be reported to userspace.
  5102. */
  5103. return !write_fault_to_shadow_pgtable;
  5104. }
  5105. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  5106. unsigned long cr2, int emulation_type)
  5107. {
  5108. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5109. unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  5110. last_retry_eip = vcpu->arch.last_retry_eip;
  5111. last_retry_addr = vcpu->arch.last_retry_addr;
  5112. /*
  5113. * If the emulation is caused by #PF and it is non-page_table
  5114. * writing instruction, it means the VM-EXIT is caused by shadow
  5115. * page protected, we can zap the shadow page and retry this
  5116. * instruction directly.
  5117. *
  5118. * Note: if the guest uses a non-page-table modifying instruction
  5119. * on the PDE that points to the instruction, then we will unmap
  5120. * the instruction and go to an infinite loop. So, we cache the
  5121. * last retried eip and the last fault address, if we meet the eip
  5122. * and the address again, we can break out of the potential infinite
  5123. * loop.
  5124. */
  5125. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  5126. if (!(emulation_type & EMULTYPE_RETRY))
  5127. return false;
  5128. if (x86_page_table_writing_insn(ctxt))
  5129. return false;
  5130. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  5131. return false;
  5132. vcpu->arch.last_retry_eip = ctxt->eip;
  5133. vcpu->arch.last_retry_addr = cr2;
  5134. if (!vcpu->arch.mmu.direct_map)
  5135. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  5136. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5137. return true;
  5138. }
  5139. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  5140. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  5141. static void kvm_smm_changed(struct kvm_vcpu *vcpu)
  5142. {
  5143. if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
  5144. /* This is a good place to trace that we are exiting SMM. */
  5145. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
  5146. /* Process a latched INIT or SMI, if any. */
  5147. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5148. }
  5149. kvm_mmu_reset_context(vcpu);
  5150. }
  5151. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
  5152. {
  5153. unsigned changed = vcpu->arch.hflags ^ emul_flags;
  5154. vcpu->arch.hflags = emul_flags;
  5155. if (changed & HF_SMM_MASK)
  5156. kvm_smm_changed(vcpu);
  5157. }
  5158. static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
  5159. unsigned long *db)
  5160. {
  5161. u32 dr6 = 0;
  5162. int i;
  5163. u32 enable, rwlen;
  5164. enable = dr7;
  5165. rwlen = dr7 >> 16;
  5166. for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
  5167. if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
  5168. dr6 |= (1 << i);
  5169. return dr6;
  5170. }
  5171. static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
  5172. {
  5173. struct kvm_run *kvm_run = vcpu->run;
  5174. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
  5175. kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
  5176. kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
  5177. kvm_run->debug.arch.exception = DB_VECTOR;
  5178. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  5179. *r = EMULATE_USER_EXIT;
  5180. } else {
  5181. /*
  5182. * "Certain debug exceptions may clear bit 0-3. The
  5183. * remaining contents of the DR6 register are never
  5184. * cleared by the processor".
  5185. */
  5186. vcpu->arch.dr6 &= ~15;
  5187. vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
  5188. kvm_queue_exception(vcpu, DB_VECTOR);
  5189. }
  5190. }
  5191. int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  5192. {
  5193. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  5194. int r = EMULATE_DONE;
  5195. kvm_x86_ops->skip_emulated_instruction(vcpu);
  5196. /*
  5197. * rflags is the old, "raw" value of the flags. The new value has
  5198. * not been saved yet.
  5199. *
  5200. * This is correct even for TF set by the guest, because "the
  5201. * processor will not generate this exception after the instruction
  5202. * that sets the TF flag".
  5203. */
  5204. if (unlikely(rflags & X86_EFLAGS_TF))
  5205. kvm_vcpu_do_singlestep(vcpu, &r);
  5206. return r == EMULATE_DONE;
  5207. }
  5208. EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
  5209. static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
  5210. {
  5211. if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
  5212. (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
  5213. struct kvm_run *kvm_run = vcpu->run;
  5214. unsigned long eip = kvm_get_linear_rip(vcpu);
  5215. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  5216. vcpu->arch.guest_debug_dr7,
  5217. vcpu->arch.eff_db);
  5218. if (dr6 != 0) {
  5219. kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
  5220. kvm_run->debug.arch.pc = eip;
  5221. kvm_run->debug.arch.exception = DB_VECTOR;
  5222. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  5223. *r = EMULATE_USER_EXIT;
  5224. return true;
  5225. }
  5226. }
  5227. if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
  5228. !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
  5229. unsigned long eip = kvm_get_linear_rip(vcpu);
  5230. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  5231. vcpu->arch.dr7,
  5232. vcpu->arch.db);
  5233. if (dr6 != 0) {
  5234. vcpu->arch.dr6 &= ~15;
  5235. vcpu->arch.dr6 |= dr6 | DR6_RTM;
  5236. kvm_queue_exception(vcpu, DB_VECTOR);
  5237. *r = EMULATE_DONE;
  5238. return true;
  5239. }
  5240. }
  5241. return false;
  5242. }
  5243. static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
  5244. {
  5245. switch (ctxt->opcode_len) {
  5246. case 1:
  5247. switch (ctxt->b) {
  5248. case 0xe4: /* IN */
  5249. case 0xe5:
  5250. case 0xec:
  5251. case 0xed:
  5252. case 0xe6: /* OUT */
  5253. case 0xe7:
  5254. case 0xee:
  5255. case 0xef:
  5256. case 0x6c: /* INS */
  5257. case 0x6d:
  5258. case 0x6e: /* OUTS */
  5259. case 0x6f:
  5260. return true;
  5261. }
  5262. break;
  5263. case 2:
  5264. switch (ctxt->b) {
  5265. case 0x33: /* RDPMC */
  5266. return true;
  5267. }
  5268. break;
  5269. }
  5270. return false;
  5271. }
  5272. int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  5273. unsigned long cr2,
  5274. int emulation_type,
  5275. void *insn,
  5276. int insn_len)
  5277. {
  5278. int r;
  5279. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5280. bool writeback = true;
  5281. bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
  5282. /*
  5283. * Clear write_fault_to_shadow_pgtable here to ensure it is
  5284. * never reused.
  5285. */
  5286. vcpu->arch.write_fault_to_shadow_pgtable = false;
  5287. kvm_clear_exception_queue(vcpu);
  5288. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  5289. init_emulate_ctxt(vcpu);
  5290. /*
  5291. * We will reenter on the same instruction since
  5292. * we do not set complete_userspace_io. This does not
  5293. * handle watchpoints yet, those would be handled in
  5294. * the emulate_ops.
  5295. */
  5296. if (!(emulation_type & EMULTYPE_SKIP) &&
  5297. kvm_vcpu_check_breakpoint(vcpu, &r))
  5298. return r;
  5299. ctxt->interruptibility = 0;
  5300. ctxt->have_exception = false;
  5301. ctxt->exception.vector = -1;
  5302. ctxt->perm_ok = false;
  5303. ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
  5304. r = x86_decode_insn(ctxt, insn, insn_len);
  5305. trace_kvm_emulate_insn_start(vcpu);
  5306. ++vcpu->stat.insn_emulation;
  5307. if (r != EMULATION_OK) {
  5308. if (emulation_type & EMULTYPE_TRAP_UD)
  5309. return EMULATE_FAIL;
  5310. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  5311. emulation_type))
  5312. return EMULATE_DONE;
  5313. if (ctxt->have_exception && inject_emulated_exception(vcpu))
  5314. return EMULATE_DONE;
  5315. if (emulation_type & EMULTYPE_SKIP)
  5316. return EMULATE_FAIL;
  5317. return handle_emulation_failure(vcpu, emulation_type);
  5318. }
  5319. }
  5320. if ((emulation_type & EMULTYPE_VMWARE) &&
  5321. !is_vmware_backdoor_opcode(ctxt))
  5322. return EMULATE_FAIL;
  5323. if (emulation_type & EMULTYPE_SKIP) {
  5324. kvm_rip_write(vcpu, ctxt->_eip);
  5325. if (ctxt->eflags & X86_EFLAGS_RF)
  5326. kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
  5327. return EMULATE_DONE;
  5328. }
  5329. if (retry_instruction(ctxt, cr2, emulation_type))
  5330. return EMULATE_DONE;
  5331. /* this is needed for vmware backdoor interface to work since it
  5332. changes registers values during IO operation */
  5333. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  5334. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  5335. emulator_invalidate_register_cache(ctxt);
  5336. }
  5337. restart:
  5338. /* Save the faulting GPA (cr2) in the address field */
  5339. ctxt->exception.address = cr2;
  5340. r = x86_emulate_insn(ctxt);
  5341. if (r == EMULATION_INTERCEPTED)
  5342. return EMULATE_DONE;
  5343. if (r == EMULATION_FAILED) {
  5344. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  5345. emulation_type))
  5346. return EMULATE_DONE;
  5347. return handle_emulation_failure(vcpu, emulation_type);
  5348. }
  5349. if (ctxt->have_exception) {
  5350. r = EMULATE_DONE;
  5351. if (inject_emulated_exception(vcpu))
  5352. return r;
  5353. } else if (vcpu->arch.pio.count) {
  5354. if (!vcpu->arch.pio.in) {
  5355. /* FIXME: return into emulator if single-stepping. */
  5356. vcpu->arch.pio.count = 0;
  5357. } else {
  5358. writeback = false;
  5359. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  5360. }
  5361. r = EMULATE_USER_EXIT;
  5362. } else if (vcpu->mmio_needed) {
  5363. if (!vcpu->mmio_is_write)
  5364. writeback = false;
  5365. r = EMULATE_USER_EXIT;
  5366. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  5367. } else if (r == EMULATION_RESTART)
  5368. goto restart;
  5369. else
  5370. r = EMULATE_DONE;
  5371. if (writeback) {
  5372. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  5373. toggle_interruptibility(vcpu, ctxt->interruptibility);
  5374. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  5375. kvm_rip_write(vcpu, ctxt->eip);
  5376. if (r == EMULATE_DONE &&
  5377. (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
  5378. kvm_vcpu_do_singlestep(vcpu, &r);
  5379. if (!ctxt->have_exception ||
  5380. exception_type(ctxt->exception.vector) == EXCPT_TRAP)
  5381. __kvm_set_rflags(vcpu, ctxt->eflags);
  5382. /*
  5383. * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
  5384. * do nothing, and it will be requested again as soon as
  5385. * the shadow expires. But we still need to check here,
  5386. * because POPF has no interrupt shadow.
  5387. */
  5388. if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
  5389. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5390. } else
  5391. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  5392. return r;
  5393. }
  5394. EXPORT_SYMBOL_GPL(x86_emulate_instruction);
  5395. static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
  5396. unsigned short port)
  5397. {
  5398. unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5399. int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  5400. size, port, &val, 1);
  5401. /* do not return to emulator after return from userspace */
  5402. vcpu->arch.pio.count = 0;
  5403. return ret;
  5404. }
  5405. static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
  5406. {
  5407. unsigned long val;
  5408. /* We should only ever be called with arch.pio.count equal to 1 */
  5409. BUG_ON(vcpu->arch.pio.count != 1);
  5410. /* For size less than 4 we merge, else we zero extend */
  5411. val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
  5412. : 0;
  5413. /*
  5414. * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
  5415. * the copy and tracing
  5416. */
  5417. emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
  5418. vcpu->arch.pio.port, &val, 1);
  5419. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  5420. return 1;
  5421. }
  5422. static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
  5423. unsigned short port)
  5424. {
  5425. unsigned long val;
  5426. int ret;
  5427. /* For size less than 4 we merge, else we zero extend */
  5428. val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
  5429. ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
  5430. &val, 1);
  5431. if (ret) {
  5432. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  5433. return ret;
  5434. }
  5435. vcpu->arch.complete_userspace_io = complete_fast_pio_in;
  5436. return 0;
  5437. }
  5438. int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
  5439. {
  5440. int ret = kvm_skip_emulated_instruction(vcpu);
  5441. /*
  5442. * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
  5443. * KVM_EXIT_DEBUG here.
  5444. */
  5445. if (in)
  5446. return kvm_fast_pio_in(vcpu, size, port) && ret;
  5447. else
  5448. return kvm_fast_pio_out(vcpu, size, port) && ret;
  5449. }
  5450. EXPORT_SYMBOL_GPL(kvm_fast_pio);
  5451. static int kvmclock_cpu_down_prep(unsigned int cpu)
  5452. {
  5453. __this_cpu_write(cpu_tsc_khz, 0);
  5454. return 0;
  5455. }
  5456. static void tsc_khz_changed(void *data)
  5457. {
  5458. struct cpufreq_freqs *freq = data;
  5459. unsigned long khz = 0;
  5460. if (data)
  5461. khz = freq->new;
  5462. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5463. khz = cpufreq_quick_get(raw_smp_processor_id());
  5464. if (!khz)
  5465. khz = tsc_khz;
  5466. __this_cpu_write(cpu_tsc_khz, khz);
  5467. }
  5468. #ifdef CONFIG_X86_64
  5469. static void kvm_hyperv_tsc_notifier(void)
  5470. {
  5471. struct kvm *kvm;
  5472. struct kvm_vcpu *vcpu;
  5473. int cpu;
  5474. spin_lock(&kvm_lock);
  5475. list_for_each_entry(kvm, &vm_list, vm_list)
  5476. kvm_make_mclock_inprogress_request(kvm);
  5477. hyperv_stop_tsc_emulation();
  5478. /* TSC frequency always matches when on Hyper-V */
  5479. for_each_present_cpu(cpu)
  5480. per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
  5481. kvm_max_guest_tsc_khz = tsc_khz;
  5482. list_for_each_entry(kvm, &vm_list, vm_list) {
  5483. struct kvm_arch *ka = &kvm->arch;
  5484. spin_lock(&ka->pvclock_gtod_sync_lock);
  5485. pvclock_update_vm_gtod_copy(kvm);
  5486. kvm_for_each_vcpu(cpu, vcpu, kvm)
  5487. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5488. kvm_for_each_vcpu(cpu, vcpu, kvm)
  5489. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  5490. spin_unlock(&ka->pvclock_gtod_sync_lock);
  5491. }
  5492. spin_unlock(&kvm_lock);
  5493. }
  5494. #endif
  5495. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  5496. void *data)
  5497. {
  5498. struct cpufreq_freqs *freq = data;
  5499. struct kvm *kvm;
  5500. struct kvm_vcpu *vcpu;
  5501. int i, send_ipi = 0;
  5502. /*
  5503. * We allow guests to temporarily run on slowing clocks,
  5504. * provided we notify them after, or to run on accelerating
  5505. * clocks, provided we notify them before. Thus time never
  5506. * goes backwards.
  5507. *
  5508. * However, we have a problem. We can't atomically update
  5509. * the frequency of a given CPU from this function; it is
  5510. * merely a notifier, which can be called from any CPU.
  5511. * Changing the TSC frequency at arbitrary points in time
  5512. * requires a recomputation of local variables related to
  5513. * the TSC for each VCPU. We must flag these local variables
  5514. * to be updated and be sure the update takes place with the
  5515. * new frequency before any guests proceed.
  5516. *
  5517. * Unfortunately, the combination of hotplug CPU and frequency
  5518. * change creates an intractable locking scenario; the order
  5519. * of when these callouts happen is undefined with respect to
  5520. * CPU hotplug, and they can race with each other. As such,
  5521. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  5522. * undefined; you can actually have a CPU frequency change take
  5523. * place in between the computation of X and the setting of the
  5524. * variable. To protect against this problem, all updates of
  5525. * the per_cpu tsc_khz variable are done in an interrupt
  5526. * protected IPI, and all callers wishing to update the value
  5527. * must wait for a synchronous IPI to complete (which is trivial
  5528. * if the caller is on the CPU already). This establishes the
  5529. * necessary total order on variable updates.
  5530. *
  5531. * Note that because a guest time update may take place
  5532. * anytime after the setting of the VCPU's request bit, the
  5533. * correct TSC value must be set before the request. However,
  5534. * to ensure the update actually makes it to any guest which
  5535. * starts running in hardware virtualization between the set
  5536. * and the acquisition of the spinlock, we must also ping the
  5537. * CPU after setting the request bit.
  5538. *
  5539. */
  5540. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  5541. return 0;
  5542. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  5543. return 0;
  5544. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5545. spin_lock(&kvm_lock);
  5546. list_for_each_entry(kvm, &vm_list, vm_list) {
  5547. kvm_for_each_vcpu(i, vcpu, kvm) {
  5548. if (vcpu->cpu != freq->cpu)
  5549. continue;
  5550. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5551. if (vcpu->cpu != smp_processor_id())
  5552. send_ipi = 1;
  5553. }
  5554. }
  5555. spin_unlock(&kvm_lock);
  5556. if (freq->old < freq->new && send_ipi) {
  5557. /*
  5558. * We upscale the frequency. Must make the guest
  5559. * doesn't see old kvmclock values while running with
  5560. * the new frequency, otherwise we risk the guest sees
  5561. * time go backwards.
  5562. *
  5563. * In case we update the frequency for another cpu
  5564. * (which might be in guest context) send an interrupt
  5565. * to kick the cpu out of guest context. Next time
  5566. * guest context is entered kvmclock will be updated,
  5567. * so the guest will not see stale values.
  5568. */
  5569. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5570. }
  5571. return 0;
  5572. }
  5573. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  5574. .notifier_call = kvmclock_cpufreq_notifier
  5575. };
  5576. static int kvmclock_cpu_online(unsigned int cpu)
  5577. {
  5578. tsc_khz_changed(NULL);
  5579. return 0;
  5580. }
  5581. static void kvm_timer_init(void)
  5582. {
  5583. max_tsc_khz = tsc_khz;
  5584. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  5585. #ifdef CONFIG_CPU_FREQ
  5586. struct cpufreq_policy policy;
  5587. int cpu;
  5588. memset(&policy, 0, sizeof(policy));
  5589. cpu = get_cpu();
  5590. cpufreq_get_policy(&policy, cpu);
  5591. if (policy.cpuinfo.max_freq)
  5592. max_tsc_khz = policy.cpuinfo.max_freq;
  5593. put_cpu();
  5594. #endif
  5595. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  5596. CPUFREQ_TRANSITION_NOTIFIER);
  5597. }
  5598. pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
  5599. cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
  5600. kvmclock_cpu_online, kvmclock_cpu_down_prep);
  5601. }
  5602. DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
  5603. EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
  5604. int kvm_is_in_guest(void)
  5605. {
  5606. return __this_cpu_read(current_vcpu) != NULL;
  5607. }
  5608. static int kvm_is_user_mode(void)
  5609. {
  5610. int user_mode = 3;
  5611. if (__this_cpu_read(current_vcpu))
  5612. user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
  5613. return user_mode != 0;
  5614. }
  5615. static unsigned long kvm_get_guest_ip(void)
  5616. {
  5617. unsigned long ip = 0;
  5618. if (__this_cpu_read(current_vcpu))
  5619. ip = kvm_rip_read(__this_cpu_read(current_vcpu));
  5620. return ip;
  5621. }
  5622. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  5623. .is_in_guest = kvm_is_in_guest,
  5624. .is_user_mode = kvm_is_user_mode,
  5625. .get_guest_ip = kvm_get_guest_ip,
  5626. };
  5627. static void kvm_set_mmio_spte_mask(void)
  5628. {
  5629. u64 mask;
  5630. int maxphyaddr = boot_cpu_data.x86_phys_bits;
  5631. /*
  5632. * Set the reserved bits and the present bit of an paging-structure
  5633. * entry to generate page fault with PFER.RSV = 1.
  5634. */
  5635. /*
  5636. * Mask the uppermost physical address bit, which would be reserved as
  5637. * long as the supported physical address width is less than 52.
  5638. */
  5639. mask = 1ull << 51;
  5640. /* Set the present bit. */
  5641. mask |= 1ull;
  5642. #ifdef CONFIG_X86_64
  5643. /*
  5644. * If reserved bit is not supported, clear the present bit to disable
  5645. * mmio page fault.
  5646. */
  5647. if (maxphyaddr == 52)
  5648. mask &= ~1ull;
  5649. #endif
  5650. kvm_mmu_set_mmio_spte_mask(mask, mask);
  5651. }
  5652. #ifdef CONFIG_X86_64
  5653. static void pvclock_gtod_update_fn(struct work_struct *work)
  5654. {
  5655. struct kvm *kvm;
  5656. struct kvm_vcpu *vcpu;
  5657. int i;
  5658. spin_lock(&kvm_lock);
  5659. list_for_each_entry(kvm, &vm_list, vm_list)
  5660. kvm_for_each_vcpu(i, vcpu, kvm)
  5661. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  5662. atomic_set(&kvm_guest_has_master_clock, 0);
  5663. spin_unlock(&kvm_lock);
  5664. }
  5665. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  5666. /*
  5667. * Notification about pvclock gtod data update.
  5668. */
  5669. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  5670. void *priv)
  5671. {
  5672. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  5673. struct timekeeper *tk = priv;
  5674. update_pvclock_gtod(tk);
  5675. /* disable master clock if host does not trust, or does not
  5676. * use, TSC based clocksource.
  5677. */
  5678. if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
  5679. atomic_read(&kvm_guest_has_master_clock) != 0)
  5680. queue_work(system_long_wq, &pvclock_gtod_work);
  5681. return 0;
  5682. }
  5683. static struct notifier_block pvclock_gtod_notifier = {
  5684. .notifier_call = pvclock_gtod_notify,
  5685. };
  5686. #endif
  5687. int kvm_arch_init(void *opaque)
  5688. {
  5689. int r;
  5690. struct kvm_x86_ops *ops = opaque;
  5691. if (kvm_x86_ops) {
  5692. printk(KERN_ERR "kvm: already loaded the other module\n");
  5693. r = -EEXIST;
  5694. goto out;
  5695. }
  5696. if (!ops->cpu_has_kvm_support()) {
  5697. printk(KERN_ERR "kvm: no hardware support\n");
  5698. r = -EOPNOTSUPP;
  5699. goto out;
  5700. }
  5701. if (ops->disabled_by_bios()) {
  5702. printk(KERN_ERR "kvm: disabled by bios\n");
  5703. r = -EOPNOTSUPP;
  5704. goto out;
  5705. }
  5706. r = -ENOMEM;
  5707. shared_msrs = alloc_percpu(struct kvm_shared_msrs);
  5708. if (!shared_msrs) {
  5709. printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
  5710. goto out;
  5711. }
  5712. r = kvm_mmu_module_init();
  5713. if (r)
  5714. goto out_free_percpu;
  5715. kvm_set_mmio_spte_mask();
  5716. kvm_x86_ops = ops;
  5717. kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
  5718. PT_DIRTY_MASK, PT64_NX_MASK, 0,
  5719. PT_PRESENT_MASK, 0, sme_me_mask);
  5720. kvm_timer_init();
  5721. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  5722. if (boot_cpu_has(X86_FEATURE_XSAVE))
  5723. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  5724. kvm_lapic_init();
  5725. #ifdef CONFIG_X86_64
  5726. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  5727. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  5728. set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
  5729. #endif
  5730. return 0;
  5731. out_free_percpu:
  5732. free_percpu(shared_msrs);
  5733. out:
  5734. return r;
  5735. }
  5736. void kvm_arch_exit(void)
  5737. {
  5738. #ifdef CONFIG_X86_64
  5739. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  5740. clear_hv_tscchange_cb();
  5741. #endif
  5742. kvm_lapic_exit();
  5743. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  5744. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5745. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  5746. CPUFREQ_TRANSITION_NOTIFIER);
  5747. cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
  5748. #ifdef CONFIG_X86_64
  5749. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  5750. #endif
  5751. kvm_x86_ops = NULL;
  5752. kvm_mmu_module_exit();
  5753. free_percpu(shared_msrs);
  5754. }
  5755. int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
  5756. {
  5757. ++vcpu->stat.halt_exits;
  5758. if (lapic_in_kernel(vcpu)) {
  5759. vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
  5760. return 1;
  5761. } else {
  5762. vcpu->run->exit_reason = KVM_EXIT_HLT;
  5763. return 0;
  5764. }
  5765. }
  5766. EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
  5767. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  5768. {
  5769. int ret = kvm_skip_emulated_instruction(vcpu);
  5770. /*
  5771. * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
  5772. * KVM_EXIT_DEBUG here.
  5773. */
  5774. return kvm_vcpu_halt(vcpu) && ret;
  5775. }
  5776. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  5777. #ifdef CONFIG_X86_64
  5778. static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
  5779. unsigned long clock_type)
  5780. {
  5781. struct kvm_clock_pairing clock_pairing;
  5782. struct timespec64 ts;
  5783. u64 cycle;
  5784. int ret;
  5785. if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
  5786. return -KVM_EOPNOTSUPP;
  5787. if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
  5788. return -KVM_EOPNOTSUPP;
  5789. clock_pairing.sec = ts.tv_sec;
  5790. clock_pairing.nsec = ts.tv_nsec;
  5791. clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
  5792. clock_pairing.flags = 0;
  5793. ret = 0;
  5794. if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
  5795. sizeof(struct kvm_clock_pairing)))
  5796. ret = -KVM_EFAULT;
  5797. return ret;
  5798. }
  5799. #endif
  5800. /*
  5801. * kvm_pv_kick_cpu_op: Kick a vcpu.
  5802. *
  5803. * @apicid - apicid of vcpu to be kicked.
  5804. */
  5805. static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
  5806. {
  5807. struct kvm_lapic_irq lapic_irq;
  5808. lapic_irq.shorthand = 0;
  5809. lapic_irq.dest_mode = 0;
  5810. lapic_irq.level = 0;
  5811. lapic_irq.dest_id = apicid;
  5812. lapic_irq.msi_redir_hint = false;
  5813. lapic_irq.delivery_mode = APIC_DM_REMRD;
  5814. kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
  5815. }
  5816. void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
  5817. {
  5818. vcpu->arch.apicv_active = false;
  5819. kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
  5820. }
  5821. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  5822. {
  5823. unsigned long nr, a0, a1, a2, a3, ret;
  5824. int op_64_bit;
  5825. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  5826. return kvm_hv_hypercall(vcpu);
  5827. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5828. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  5829. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  5830. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  5831. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  5832. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  5833. op_64_bit = is_64_bit_mode(vcpu);
  5834. if (!op_64_bit) {
  5835. nr &= 0xFFFFFFFF;
  5836. a0 &= 0xFFFFFFFF;
  5837. a1 &= 0xFFFFFFFF;
  5838. a2 &= 0xFFFFFFFF;
  5839. a3 &= 0xFFFFFFFF;
  5840. }
  5841. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  5842. ret = -KVM_EPERM;
  5843. goto out;
  5844. }
  5845. switch (nr) {
  5846. case KVM_HC_VAPIC_POLL_IRQ:
  5847. ret = 0;
  5848. break;
  5849. case KVM_HC_KICK_CPU:
  5850. kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
  5851. ret = 0;
  5852. break;
  5853. #ifdef CONFIG_X86_64
  5854. case KVM_HC_CLOCK_PAIRING:
  5855. ret = kvm_pv_clock_pairing(vcpu, a0, a1);
  5856. break;
  5857. case KVM_HC_SEND_IPI:
  5858. ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
  5859. break;
  5860. #endif
  5861. default:
  5862. ret = -KVM_ENOSYS;
  5863. break;
  5864. }
  5865. out:
  5866. if (!op_64_bit)
  5867. ret = (u32)ret;
  5868. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  5869. ++vcpu->stat.hypercalls;
  5870. return kvm_skip_emulated_instruction(vcpu);
  5871. }
  5872. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  5873. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  5874. {
  5875. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5876. char instruction[3];
  5877. unsigned long rip = kvm_rip_read(vcpu);
  5878. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  5879. return emulator_write_emulated(ctxt, rip, instruction, 3,
  5880. &ctxt->exception);
  5881. }
  5882. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  5883. {
  5884. return vcpu->run->request_interrupt_window &&
  5885. likely(!pic_in_kernel(vcpu->kvm));
  5886. }
  5887. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  5888. {
  5889. struct kvm_run *kvm_run = vcpu->run;
  5890. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  5891. kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
  5892. kvm_run->cr8 = kvm_get_cr8(vcpu);
  5893. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  5894. kvm_run->ready_for_interrupt_injection =
  5895. pic_in_kernel(vcpu->kvm) ||
  5896. kvm_vcpu_ready_for_interrupt_injection(vcpu);
  5897. }
  5898. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  5899. {
  5900. int max_irr, tpr;
  5901. if (!kvm_x86_ops->update_cr8_intercept)
  5902. return;
  5903. if (!lapic_in_kernel(vcpu))
  5904. return;
  5905. if (vcpu->arch.apicv_active)
  5906. return;
  5907. if (!vcpu->arch.apic->vapic_addr)
  5908. max_irr = kvm_lapic_find_highest_irr(vcpu);
  5909. else
  5910. max_irr = -1;
  5911. if (max_irr != -1)
  5912. max_irr >>= 4;
  5913. tpr = kvm_lapic_get_cr8(vcpu);
  5914. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  5915. }
  5916. static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
  5917. {
  5918. int r;
  5919. /* try to reinject previous events if any */
  5920. if (vcpu->arch.exception.injected)
  5921. kvm_x86_ops->queue_exception(vcpu);
  5922. /*
  5923. * Do not inject an NMI or interrupt if there is a pending
  5924. * exception. Exceptions and interrupts are recognized at
  5925. * instruction boundaries, i.e. the start of an instruction.
  5926. * Trap-like exceptions, e.g. #DB, have higher priority than
  5927. * NMIs and interrupts, i.e. traps are recognized before an
  5928. * NMI/interrupt that's pending on the same instruction.
  5929. * Fault-like exceptions, e.g. #GP and #PF, are the lowest
  5930. * priority, but are only generated (pended) during instruction
  5931. * execution, i.e. a pending fault-like exception means the
  5932. * fault occurred on the *previous* instruction and must be
  5933. * serviced prior to recognizing any new events in order to
  5934. * fully complete the previous instruction.
  5935. */
  5936. else if (!vcpu->arch.exception.pending) {
  5937. if (vcpu->arch.nmi_injected)
  5938. kvm_x86_ops->set_nmi(vcpu);
  5939. else if (vcpu->arch.interrupt.injected)
  5940. kvm_x86_ops->set_irq(vcpu);
  5941. }
  5942. /*
  5943. * Call check_nested_events() even if we reinjected a previous event
  5944. * in order for caller to determine if it should require immediate-exit
  5945. * from L2 to L1 due to pending L1 events which require exit
  5946. * from L2 to L1.
  5947. */
  5948. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5949. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5950. if (r != 0)
  5951. return r;
  5952. }
  5953. /* try to inject new event if pending */
  5954. if (vcpu->arch.exception.pending) {
  5955. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  5956. vcpu->arch.exception.has_error_code,
  5957. vcpu->arch.exception.error_code);
  5958. WARN_ON_ONCE(vcpu->arch.exception.injected);
  5959. vcpu->arch.exception.pending = false;
  5960. vcpu->arch.exception.injected = true;
  5961. if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
  5962. __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
  5963. X86_EFLAGS_RF);
  5964. if (vcpu->arch.exception.nr == DB_VECTOR &&
  5965. (vcpu->arch.dr7 & DR7_GD)) {
  5966. vcpu->arch.dr7 &= ~DR7_GD;
  5967. kvm_update_dr7(vcpu);
  5968. }
  5969. kvm_x86_ops->queue_exception(vcpu);
  5970. }
  5971. /* Don't consider new event if we re-injected an event */
  5972. if (kvm_event_needs_reinjection(vcpu))
  5973. return 0;
  5974. if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
  5975. kvm_x86_ops->smi_allowed(vcpu)) {
  5976. vcpu->arch.smi_pending = false;
  5977. ++vcpu->arch.smi_count;
  5978. enter_smm(vcpu);
  5979. } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
  5980. --vcpu->arch.nmi_pending;
  5981. vcpu->arch.nmi_injected = true;
  5982. kvm_x86_ops->set_nmi(vcpu);
  5983. } else if (kvm_cpu_has_injectable_intr(vcpu)) {
  5984. /*
  5985. * Because interrupts can be injected asynchronously, we are
  5986. * calling check_nested_events again here to avoid a race condition.
  5987. * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
  5988. * proposal and current concerns. Perhaps we should be setting
  5989. * KVM_REQ_EVENT only on certain events and not unconditionally?
  5990. */
  5991. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5992. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5993. if (r != 0)
  5994. return r;
  5995. }
  5996. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  5997. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  5998. false);
  5999. kvm_x86_ops->set_irq(vcpu);
  6000. }
  6001. }
  6002. return 0;
  6003. }
  6004. static void process_nmi(struct kvm_vcpu *vcpu)
  6005. {
  6006. unsigned limit = 2;
  6007. /*
  6008. * x86 is limited to one NMI running, and one NMI pending after it.
  6009. * If an NMI is already in progress, limit further NMIs to just one.
  6010. * Otherwise, allow two (and we'll inject the first one immediately).
  6011. */
  6012. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  6013. limit = 1;
  6014. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  6015. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  6016. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6017. }
  6018. static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
  6019. {
  6020. u32 flags = 0;
  6021. flags |= seg->g << 23;
  6022. flags |= seg->db << 22;
  6023. flags |= seg->l << 21;
  6024. flags |= seg->avl << 20;
  6025. flags |= seg->present << 15;
  6026. flags |= seg->dpl << 13;
  6027. flags |= seg->s << 12;
  6028. flags |= seg->type << 8;
  6029. return flags;
  6030. }
  6031. static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
  6032. {
  6033. struct kvm_segment seg;
  6034. int offset;
  6035. kvm_get_segment(vcpu, &seg, n);
  6036. put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
  6037. if (n < 3)
  6038. offset = 0x7f84 + n * 12;
  6039. else
  6040. offset = 0x7f2c + (n - 3) * 12;
  6041. put_smstate(u32, buf, offset + 8, seg.base);
  6042. put_smstate(u32, buf, offset + 4, seg.limit);
  6043. put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
  6044. }
  6045. #ifdef CONFIG_X86_64
  6046. static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
  6047. {
  6048. struct kvm_segment seg;
  6049. int offset;
  6050. u16 flags;
  6051. kvm_get_segment(vcpu, &seg, n);
  6052. offset = 0x7e00 + n * 16;
  6053. flags = enter_smm_get_segment_flags(&seg) >> 8;
  6054. put_smstate(u16, buf, offset, seg.selector);
  6055. put_smstate(u16, buf, offset + 2, flags);
  6056. put_smstate(u32, buf, offset + 4, seg.limit);
  6057. put_smstate(u64, buf, offset + 8, seg.base);
  6058. }
  6059. #endif
  6060. static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
  6061. {
  6062. struct desc_ptr dt;
  6063. struct kvm_segment seg;
  6064. unsigned long val;
  6065. int i;
  6066. put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
  6067. put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
  6068. put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
  6069. put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
  6070. for (i = 0; i < 8; i++)
  6071. put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
  6072. kvm_get_dr(vcpu, 6, &val);
  6073. put_smstate(u32, buf, 0x7fcc, (u32)val);
  6074. kvm_get_dr(vcpu, 7, &val);
  6075. put_smstate(u32, buf, 0x7fc8, (u32)val);
  6076. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  6077. put_smstate(u32, buf, 0x7fc4, seg.selector);
  6078. put_smstate(u32, buf, 0x7f64, seg.base);
  6079. put_smstate(u32, buf, 0x7f60, seg.limit);
  6080. put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
  6081. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  6082. put_smstate(u32, buf, 0x7fc0, seg.selector);
  6083. put_smstate(u32, buf, 0x7f80, seg.base);
  6084. put_smstate(u32, buf, 0x7f7c, seg.limit);
  6085. put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
  6086. kvm_x86_ops->get_gdt(vcpu, &dt);
  6087. put_smstate(u32, buf, 0x7f74, dt.address);
  6088. put_smstate(u32, buf, 0x7f70, dt.size);
  6089. kvm_x86_ops->get_idt(vcpu, &dt);
  6090. put_smstate(u32, buf, 0x7f58, dt.address);
  6091. put_smstate(u32, buf, 0x7f54, dt.size);
  6092. for (i = 0; i < 6; i++)
  6093. enter_smm_save_seg_32(vcpu, buf, i);
  6094. put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
  6095. /* revision id */
  6096. put_smstate(u32, buf, 0x7efc, 0x00020000);
  6097. put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
  6098. }
  6099. static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
  6100. {
  6101. #ifdef CONFIG_X86_64
  6102. struct desc_ptr dt;
  6103. struct kvm_segment seg;
  6104. unsigned long val;
  6105. int i;
  6106. for (i = 0; i < 16; i++)
  6107. put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
  6108. put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
  6109. put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
  6110. kvm_get_dr(vcpu, 6, &val);
  6111. put_smstate(u64, buf, 0x7f68, val);
  6112. kvm_get_dr(vcpu, 7, &val);
  6113. put_smstate(u64, buf, 0x7f60, val);
  6114. put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
  6115. put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
  6116. put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
  6117. put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
  6118. /* revision id */
  6119. put_smstate(u32, buf, 0x7efc, 0x00020064);
  6120. put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
  6121. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  6122. put_smstate(u16, buf, 0x7e90, seg.selector);
  6123. put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
  6124. put_smstate(u32, buf, 0x7e94, seg.limit);
  6125. put_smstate(u64, buf, 0x7e98, seg.base);
  6126. kvm_x86_ops->get_idt(vcpu, &dt);
  6127. put_smstate(u32, buf, 0x7e84, dt.size);
  6128. put_smstate(u64, buf, 0x7e88, dt.address);
  6129. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  6130. put_smstate(u16, buf, 0x7e70, seg.selector);
  6131. put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
  6132. put_smstate(u32, buf, 0x7e74, seg.limit);
  6133. put_smstate(u64, buf, 0x7e78, seg.base);
  6134. kvm_x86_ops->get_gdt(vcpu, &dt);
  6135. put_smstate(u32, buf, 0x7e64, dt.size);
  6136. put_smstate(u64, buf, 0x7e68, dt.address);
  6137. for (i = 0; i < 6; i++)
  6138. enter_smm_save_seg_64(vcpu, buf, i);
  6139. #else
  6140. WARN_ON_ONCE(1);
  6141. #endif
  6142. }
  6143. static void enter_smm(struct kvm_vcpu *vcpu)
  6144. {
  6145. struct kvm_segment cs, ds;
  6146. struct desc_ptr dt;
  6147. char buf[512];
  6148. u32 cr0;
  6149. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
  6150. memset(buf, 0, 512);
  6151. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  6152. enter_smm_save_state_64(vcpu, buf);
  6153. else
  6154. enter_smm_save_state_32(vcpu, buf);
  6155. /*
  6156. * Give pre_enter_smm() a chance to make ISA-specific changes to the
  6157. * vCPU state (e.g. leave guest mode) after we've saved the state into
  6158. * the SMM state-save area.
  6159. */
  6160. kvm_x86_ops->pre_enter_smm(vcpu, buf);
  6161. vcpu->arch.hflags |= HF_SMM_MASK;
  6162. kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
  6163. if (kvm_x86_ops->get_nmi_mask(vcpu))
  6164. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  6165. else
  6166. kvm_x86_ops->set_nmi_mask(vcpu, true);
  6167. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  6168. kvm_rip_write(vcpu, 0x8000);
  6169. cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
  6170. kvm_x86_ops->set_cr0(vcpu, cr0);
  6171. vcpu->arch.cr0 = cr0;
  6172. kvm_x86_ops->set_cr4(vcpu, 0);
  6173. /* Undocumented: IDT limit is set to zero on entry to SMM. */
  6174. dt.address = dt.size = 0;
  6175. kvm_x86_ops->set_idt(vcpu, &dt);
  6176. __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
  6177. cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
  6178. cs.base = vcpu->arch.smbase;
  6179. ds.selector = 0;
  6180. ds.base = 0;
  6181. cs.limit = ds.limit = 0xffffffff;
  6182. cs.type = ds.type = 0x3;
  6183. cs.dpl = ds.dpl = 0;
  6184. cs.db = ds.db = 0;
  6185. cs.s = ds.s = 1;
  6186. cs.l = ds.l = 0;
  6187. cs.g = ds.g = 1;
  6188. cs.avl = ds.avl = 0;
  6189. cs.present = ds.present = 1;
  6190. cs.unusable = ds.unusable = 0;
  6191. cs.padding = ds.padding = 0;
  6192. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  6193. kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
  6194. kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
  6195. kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
  6196. kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
  6197. kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
  6198. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  6199. kvm_x86_ops->set_efer(vcpu, 0);
  6200. kvm_update_cpuid(vcpu);
  6201. kvm_mmu_reset_context(vcpu);
  6202. }
  6203. static void process_smi(struct kvm_vcpu *vcpu)
  6204. {
  6205. vcpu->arch.smi_pending = true;
  6206. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6207. }
  6208. void kvm_make_scan_ioapic_request(struct kvm *kvm)
  6209. {
  6210. kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
  6211. }
  6212. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  6213. {
  6214. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  6215. return;
  6216. bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
  6217. if (irqchip_split(vcpu->kvm))
  6218. kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
  6219. else {
  6220. if (vcpu->arch.apicv_active)
  6221. kvm_x86_ops->sync_pir_to_irr(vcpu);
  6222. kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
  6223. }
  6224. if (is_guest_mode(vcpu))
  6225. vcpu->arch.load_eoi_exitmap_pending = true;
  6226. else
  6227. kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
  6228. }
  6229. static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
  6230. {
  6231. u64 eoi_exit_bitmap[4];
  6232. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  6233. return;
  6234. bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
  6235. vcpu_to_synic(vcpu)->vec_bitmap, 256);
  6236. kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
  6237. }
  6238. void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
  6239. unsigned long start, unsigned long end)
  6240. {
  6241. unsigned long apic_address;
  6242. /*
  6243. * The physical address of apic access page is stored in the VMCS.
  6244. * Update it when it becomes invalid.
  6245. */
  6246. apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  6247. if (start <= apic_address && apic_address < end)
  6248. kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
  6249. }
  6250. void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
  6251. {
  6252. struct page *page = NULL;
  6253. if (!lapic_in_kernel(vcpu))
  6254. return;
  6255. if (!kvm_x86_ops->set_apic_access_page_addr)
  6256. return;
  6257. page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  6258. if (is_error_page(page))
  6259. return;
  6260. kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
  6261. /*
  6262. * Do not pin apic access page in memory, the MMU notifier
  6263. * will call us again if it is migrated or swapped out.
  6264. */
  6265. put_page(page);
  6266. }
  6267. EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
  6268. /*
  6269. * Returns 1 to let vcpu_run() continue the guest execution loop without
  6270. * exiting to the userspace. Otherwise, the value will be returned to the
  6271. * userspace.
  6272. */
  6273. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  6274. {
  6275. int r;
  6276. bool req_int_win =
  6277. dm_request_for_irq_injection(vcpu) &&
  6278. kvm_cpu_accept_dm_intr(vcpu);
  6279. bool req_immediate_exit = false;
  6280. if (kvm_request_pending(vcpu)) {
  6281. if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu))
  6282. kvm_x86_ops->get_vmcs12_pages(vcpu);
  6283. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  6284. kvm_mmu_unload(vcpu);
  6285. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  6286. __kvm_migrate_timers(vcpu);
  6287. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  6288. kvm_gen_update_masterclock(vcpu->kvm);
  6289. if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
  6290. kvm_gen_kvmclock_update(vcpu);
  6291. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  6292. r = kvm_guest_time_update(vcpu);
  6293. if (unlikely(r))
  6294. goto out;
  6295. }
  6296. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  6297. kvm_mmu_sync_roots(vcpu);
  6298. if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
  6299. kvm_mmu_load_cr3(vcpu);
  6300. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  6301. kvm_vcpu_flush_tlb(vcpu, true);
  6302. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  6303. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  6304. r = 0;
  6305. goto out;
  6306. }
  6307. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  6308. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  6309. vcpu->mmio_needed = 0;
  6310. r = 0;
  6311. goto out;
  6312. }
  6313. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  6314. /* Page is swapped out. Do synthetic halt */
  6315. vcpu->arch.apf.halted = true;
  6316. r = 1;
  6317. goto out;
  6318. }
  6319. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  6320. record_steal_time(vcpu);
  6321. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  6322. process_smi(vcpu);
  6323. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  6324. process_nmi(vcpu);
  6325. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  6326. kvm_pmu_handle_event(vcpu);
  6327. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  6328. kvm_pmu_deliver_pmi(vcpu);
  6329. if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
  6330. BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
  6331. if (test_bit(vcpu->arch.pending_ioapic_eoi,
  6332. vcpu->arch.ioapic_handled_vectors)) {
  6333. vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
  6334. vcpu->run->eoi.vector =
  6335. vcpu->arch.pending_ioapic_eoi;
  6336. r = 0;
  6337. goto out;
  6338. }
  6339. }
  6340. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  6341. vcpu_scan_ioapic(vcpu);
  6342. if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
  6343. vcpu_load_eoi_exitmap(vcpu);
  6344. if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
  6345. kvm_vcpu_reload_apic_access_page(vcpu);
  6346. if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
  6347. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  6348. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
  6349. r = 0;
  6350. goto out;
  6351. }
  6352. if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
  6353. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  6354. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
  6355. r = 0;
  6356. goto out;
  6357. }
  6358. if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
  6359. vcpu->run->exit_reason = KVM_EXIT_HYPERV;
  6360. vcpu->run->hyperv = vcpu->arch.hyperv.exit;
  6361. r = 0;
  6362. goto out;
  6363. }
  6364. /*
  6365. * KVM_REQ_HV_STIMER has to be processed after
  6366. * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
  6367. * depend on the guest clock being up-to-date
  6368. */
  6369. if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
  6370. kvm_hv_process_stimers(vcpu);
  6371. }
  6372. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  6373. ++vcpu->stat.req_event;
  6374. kvm_apic_accept_events(vcpu);
  6375. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  6376. r = 1;
  6377. goto out;
  6378. }
  6379. if (inject_pending_event(vcpu, req_int_win) != 0)
  6380. req_immediate_exit = true;
  6381. else {
  6382. /* Enable SMI/NMI/IRQ window open exits if needed.
  6383. *
  6384. * SMIs have three cases:
  6385. * 1) They can be nested, and then there is nothing to
  6386. * do here because RSM will cause a vmexit anyway.
  6387. * 2) There is an ISA-specific reason why SMI cannot be
  6388. * injected, and the moment when this changes can be
  6389. * intercepted.
  6390. * 3) Or the SMI can be pending because
  6391. * inject_pending_event has completed the injection
  6392. * of an IRQ or NMI from the previous vmexit, and
  6393. * then we request an immediate exit to inject the
  6394. * SMI.
  6395. */
  6396. if (vcpu->arch.smi_pending && !is_smm(vcpu))
  6397. if (!kvm_x86_ops->enable_smi_window(vcpu))
  6398. req_immediate_exit = true;
  6399. if (vcpu->arch.nmi_pending)
  6400. kvm_x86_ops->enable_nmi_window(vcpu);
  6401. if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
  6402. kvm_x86_ops->enable_irq_window(vcpu);
  6403. WARN_ON(vcpu->arch.exception.pending);
  6404. }
  6405. if (kvm_lapic_enabled(vcpu)) {
  6406. update_cr8_intercept(vcpu);
  6407. kvm_lapic_sync_to_vapic(vcpu);
  6408. }
  6409. }
  6410. r = kvm_mmu_reload(vcpu);
  6411. if (unlikely(r)) {
  6412. goto cancel_injection;
  6413. }
  6414. preempt_disable();
  6415. kvm_x86_ops->prepare_guest_switch(vcpu);
  6416. /*
  6417. * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
  6418. * IPI are then delayed after guest entry, which ensures that they
  6419. * result in virtual interrupt delivery.
  6420. */
  6421. local_irq_disable();
  6422. vcpu->mode = IN_GUEST_MODE;
  6423. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  6424. /*
  6425. * 1) We should set ->mode before checking ->requests. Please see
  6426. * the comment in kvm_vcpu_exiting_guest_mode().
  6427. *
  6428. * 2) For APICv, we should set ->mode before checking PIR.ON. This
  6429. * pairs with the memory barrier implicit in pi_test_and_set_on
  6430. * (see vmx_deliver_posted_interrupt).
  6431. *
  6432. * 3) This also orders the write to mode from any reads to the page
  6433. * tables done while the VCPU is running. Please see the comment
  6434. * in kvm_flush_remote_tlbs.
  6435. */
  6436. smp_mb__after_srcu_read_unlock();
  6437. /*
  6438. * This handles the case where a posted interrupt was
  6439. * notified with kvm_vcpu_kick.
  6440. */
  6441. if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
  6442. kvm_x86_ops->sync_pir_to_irr(vcpu);
  6443. if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
  6444. || need_resched() || signal_pending(current)) {
  6445. vcpu->mode = OUTSIDE_GUEST_MODE;
  6446. smp_wmb();
  6447. local_irq_enable();
  6448. preempt_enable();
  6449. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6450. r = 1;
  6451. goto cancel_injection;
  6452. }
  6453. kvm_load_guest_xcr0(vcpu);
  6454. if (req_immediate_exit) {
  6455. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6456. smp_send_reschedule(vcpu->cpu);
  6457. }
  6458. trace_kvm_entry(vcpu->vcpu_id);
  6459. if (lapic_timer_advance_ns)
  6460. wait_lapic_expire(vcpu);
  6461. guest_enter_irqoff();
  6462. if (unlikely(vcpu->arch.switch_db_regs)) {
  6463. set_debugreg(0, 7);
  6464. set_debugreg(vcpu->arch.eff_db[0], 0);
  6465. set_debugreg(vcpu->arch.eff_db[1], 1);
  6466. set_debugreg(vcpu->arch.eff_db[2], 2);
  6467. set_debugreg(vcpu->arch.eff_db[3], 3);
  6468. set_debugreg(vcpu->arch.dr6, 6);
  6469. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  6470. }
  6471. kvm_x86_ops->run(vcpu);
  6472. /*
  6473. * Do this here before restoring debug registers on the host. And
  6474. * since we do this before handling the vmexit, a DR access vmexit
  6475. * can (a) read the correct value of the debug registers, (b) set
  6476. * KVM_DEBUGREG_WONT_EXIT again.
  6477. */
  6478. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  6479. WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
  6480. kvm_x86_ops->sync_dirty_debug_regs(vcpu);
  6481. kvm_update_dr0123(vcpu);
  6482. kvm_update_dr6(vcpu);
  6483. kvm_update_dr7(vcpu);
  6484. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  6485. }
  6486. /*
  6487. * If the guest has used debug registers, at least dr7
  6488. * will be disabled while returning to the host.
  6489. * If we don't have active breakpoints in the host, we don't
  6490. * care about the messed up debug address registers. But if
  6491. * we have some of them active, restore the old state.
  6492. */
  6493. if (hw_breakpoint_active())
  6494. hw_breakpoint_restore();
  6495. vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
  6496. vcpu->mode = OUTSIDE_GUEST_MODE;
  6497. smp_wmb();
  6498. kvm_put_guest_xcr0(vcpu);
  6499. kvm_before_interrupt(vcpu);
  6500. kvm_x86_ops->handle_external_intr(vcpu);
  6501. kvm_after_interrupt(vcpu);
  6502. ++vcpu->stat.exits;
  6503. guest_exit_irqoff();
  6504. local_irq_enable();
  6505. preempt_enable();
  6506. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6507. /*
  6508. * Profile KVM exit RIPs:
  6509. */
  6510. if (unlikely(prof_on == KVM_PROFILING)) {
  6511. unsigned long rip = kvm_rip_read(vcpu);
  6512. profile_hit(KVM_PROFILING, (void *)rip);
  6513. }
  6514. if (unlikely(vcpu->arch.tsc_always_catchup))
  6515. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  6516. if (vcpu->arch.apic_attention)
  6517. kvm_lapic_sync_from_vapic(vcpu);
  6518. vcpu->arch.gpa_available = false;
  6519. r = kvm_x86_ops->handle_exit(vcpu);
  6520. return r;
  6521. cancel_injection:
  6522. kvm_x86_ops->cancel_injection(vcpu);
  6523. if (unlikely(vcpu->arch.apic_attention))
  6524. kvm_lapic_sync_from_vapic(vcpu);
  6525. out:
  6526. return r;
  6527. }
  6528. static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
  6529. {
  6530. if (!kvm_arch_vcpu_runnable(vcpu) &&
  6531. (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
  6532. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6533. kvm_vcpu_block(vcpu);
  6534. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6535. if (kvm_x86_ops->post_block)
  6536. kvm_x86_ops->post_block(vcpu);
  6537. if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
  6538. return 1;
  6539. }
  6540. kvm_apic_accept_events(vcpu);
  6541. switch(vcpu->arch.mp_state) {
  6542. case KVM_MP_STATE_HALTED:
  6543. vcpu->arch.pv.pv_unhalted = false;
  6544. vcpu->arch.mp_state =
  6545. KVM_MP_STATE_RUNNABLE;
  6546. case KVM_MP_STATE_RUNNABLE:
  6547. vcpu->arch.apf.halted = false;
  6548. break;
  6549. case KVM_MP_STATE_INIT_RECEIVED:
  6550. break;
  6551. default:
  6552. return -EINTR;
  6553. break;
  6554. }
  6555. return 1;
  6556. }
  6557. static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
  6558. {
  6559. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
  6560. kvm_x86_ops->check_nested_events(vcpu, false);
  6561. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  6562. !vcpu->arch.apf.halted);
  6563. }
  6564. static int vcpu_run(struct kvm_vcpu *vcpu)
  6565. {
  6566. int r;
  6567. struct kvm *kvm = vcpu->kvm;
  6568. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6569. for (;;) {
  6570. if (kvm_vcpu_running(vcpu)) {
  6571. r = vcpu_enter_guest(vcpu);
  6572. } else {
  6573. r = vcpu_block(kvm, vcpu);
  6574. }
  6575. if (r <= 0)
  6576. break;
  6577. kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
  6578. if (kvm_cpu_has_pending_timer(vcpu))
  6579. kvm_inject_pending_timer_irqs(vcpu);
  6580. if (dm_request_for_irq_injection(vcpu) &&
  6581. kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
  6582. r = 0;
  6583. vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
  6584. ++vcpu->stat.request_irq_exits;
  6585. break;
  6586. }
  6587. kvm_check_async_pf_completion(vcpu);
  6588. if (signal_pending(current)) {
  6589. r = -EINTR;
  6590. vcpu->run->exit_reason = KVM_EXIT_INTR;
  6591. ++vcpu->stat.signal_exits;
  6592. break;
  6593. }
  6594. if (need_resched()) {
  6595. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6596. cond_resched();
  6597. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6598. }
  6599. }
  6600. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6601. return r;
  6602. }
  6603. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  6604. {
  6605. int r;
  6606. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6607. r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  6608. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  6609. if (r != EMULATE_DONE)
  6610. return 0;
  6611. return 1;
  6612. }
  6613. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  6614. {
  6615. BUG_ON(!vcpu->arch.pio.count);
  6616. return complete_emulated_io(vcpu);
  6617. }
  6618. /*
  6619. * Implements the following, as a state machine:
  6620. *
  6621. * read:
  6622. * for each fragment
  6623. * for each mmio piece in the fragment
  6624. * write gpa, len
  6625. * exit
  6626. * copy data
  6627. * execute insn
  6628. *
  6629. * write:
  6630. * for each fragment
  6631. * for each mmio piece in the fragment
  6632. * write gpa, len
  6633. * copy data
  6634. * exit
  6635. */
  6636. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  6637. {
  6638. struct kvm_run *run = vcpu->run;
  6639. struct kvm_mmio_fragment *frag;
  6640. unsigned len;
  6641. BUG_ON(!vcpu->mmio_needed);
  6642. /* Complete previous fragment */
  6643. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  6644. len = min(8u, frag->len);
  6645. if (!vcpu->mmio_is_write)
  6646. memcpy(frag->data, run->mmio.data, len);
  6647. if (frag->len <= 8) {
  6648. /* Switch to the next fragment. */
  6649. frag++;
  6650. vcpu->mmio_cur_fragment++;
  6651. } else {
  6652. /* Go forward to the next mmio piece. */
  6653. frag->data += len;
  6654. frag->gpa += len;
  6655. frag->len -= len;
  6656. }
  6657. if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
  6658. vcpu->mmio_needed = 0;
  6659. /* FIXME: return into emulator if single-stepping. */
  6660. if (vcpu->mmio_is_write)
  6661. return 1;
  6662. vcpu->mmio_read_completed = 1;
  6663. return complete_emulated_io(vcpu);
  6664. }
  6665. run->exit_reason = KVM_EXIT_MMIO;
  6666. run->mmio.phys_addr = frag->gpa;
  6667. if (vcpu->mmio_is_write)
  6668. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  6669. run->mmio.len = min(8u, frag->len);
  6670. run->mmio.is_write = vcpu->mmio_is_write;
  6671. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  6672. return 0;
  6673. }
  6674. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  6675. {
  6676. int r;
  6677. vcpu_load(vcpu);
  6678. kvm_sigset_activate(vcpu);
  6679. kvm_load_guest_fpu(vcpu);
  6680. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  6681. if (kvm_run->immediate_exit) {
  6682. r = -EINTR;
  6683. goto out;
  6684. }
  6685. kvm_vcpu_block(vcpu);
  6686. kvm_apic_accept_events(vcpu);
  6687. kvm_clear_request(KVM_REQ_UNHALT, vcpu);
  6688. r = -EAGAIN;
  6689. if (signal_pending(current)) {
  6690. r = -EINTR;
  6691. vcpu->run->exit_reason = KVM_EXIT_INTR;
  6692. ++vcpu->stat.signal_exits;
  6693. }
  6694. goto out;
  6695. }
  6696. if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
  6697. r = -EINVAL;
  6698. goto out;
  6699. }
  6700. if (vcpu->run->kvm_dirty_regs) {
  6701. r = sync_regs(vcpu);
  6702. if (r != 0)
  6703. goto out;
  6704. }
  6705. /* re-sync apic's tpr */
  6706. if (!lapic_in_kernel(vcpu)) {
  6707. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  6708. r = -EINVAL;
  6709. goto out;
  6710. }
  6711. }
  6712. if (unlikely(vcpu->arch.complete_userspace_io)) {
  6713. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  6714. vcpu->arch.complete_userspace_io = NULL;
  6715. r = cui(vcpu);
  6716. if (r <= 0)
  6717. goto out;
  6718. } else
  6719. WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
  6720. if (kvm_run->immediate_exit)
  6721. r = -EINTR;
  6722. else
  6723. r = vcpu_run(vcpu);
  6724. out:
  6725. kvm_put_guest_fpu(vcpu);
  6726. if (vcpu->run->kvm_valid_regs)
  6727. store_regs(vcpu);
  6728. post_kvm_run_save(vcpu);
  6729. kvm_sigset_deactivate(vcpu);
  6730. vcpu_put(vcpu);
  6731. return r;
  6732. }
  6733. static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6734. {
  6735. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  6736. /*
  6737. * We are here if userspace calls get_regs() in the middle of
  6738. * instruction emulation. Registers state needs to be copied
  6739. * back from emulation context to vcpu. Userspace shouldn't do
  6740. * that usually, but some bad designed PV devices (vmware
  6741. * backdoor interface) need this to work
  6742. */
  6743. emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
  6744. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6745. }
  6746. regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  6747. regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  6748. regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  6749. regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  6750. regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  6751. regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  6752. regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  6753. regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
  6754. #ifdef CONFIG_X86_64
  6755. regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  6756. regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  6757. regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  6758. regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  6759. regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  6760. regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  6761. regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  6762. regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
  6763. #endif
  6764. regs->rip = kvm_rip_read(vcpu);
  6765. regs->rflags = kvm_get_rflags(vcpu);
  6766. }
  6767. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6768. {
  6769. vcpu_load(vcpu);
  6770. __get_regs(vcpu, regs);
  6771. vcpu_put(vcpu);
  6772. return 0;
  6773. }
  6774. static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6775. {
  6776. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  6777. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6778. kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  6779. kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  6780. kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  6781. kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  6782. kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  6783. kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  6784. kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  6785. kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
  6786. #ifdef CONFIG_X86_64
  6787. kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  6788. kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  6789. kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  6790. kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  6791. kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  6792. kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  6793. kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  6794. kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
  6795. #endif
  6796. kvm_rip_write(vcpu, regs->rip);
  6797. kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
  6798. vcpu->arch.exception.pending = false;
  6799. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6800. }
  6801. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6802. {
  6803. vcpu_load(vcpu);
  6804. __set_regs(vcpu, regs);
  6805. vcpu_put(vcpu);
  6806. return 0;
  6807. }
  6808. void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  6809. {
  6810. struct kvm_segment cs;
  6811. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  6812. *db = cs.db;
  6813. *l = cs.l;
  6814. }
  6815. EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  6816. static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  6817. {
  6818. struct desc_ptr dt;
  6819. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  6820. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  6821. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  6822. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  6823. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  6824. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  6825. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  6826. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  6827. kvm_x86_ops->get_idt(vcpu, &dt);
  6828. sregs->idt.limit = dt.size;
  6829. sregs->idt.base = dt.address;
  6830. kvm_x86_ops->get_gdt(vcpu, &dt);
  6831. sregs->gdt.limit = dt.size;
  6832. sregs->gdt.base = dt.address;
  6833. sregs->cr0 = kvm_read_cr0(vcpu);
  6834. sregs->cr2 = vcpu->arch.cr2;
  6835. sregs->cr3 = kvm_read_cr3(vcpu);
  6836. sregs->cr4 = kvm_read_cr4(vcpu);
  6837. sregs->cr8 = kvm_get_cr8(vcpu);
  6838. sregs->efer = vcpu->arch.efer;
  6839. sregs->apic_base = kvm_get_apic_base(vcpu);
  6840. memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
  6841. if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
  6842. set_bit(vcpu->arch.interrupt.nr,
  6843. (unsigned long *)sregs->interrupt_bitmap);
  6844. }
  6845. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  6846. struct kvm_sregs *sregs)
  6847. {
  6848. vcpu_load(vcpu);
  6849. __get_sregs(vcpu, sregs);
  6850. vcpu_put(vcpu);
  6851. return 0;
  6852. }
  6853. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  6854. struct kvm_mp_state *mp_state)
  6855. {
  6856. vcpu_load(vcpu);
  6857. kvm_apic_accept_events(vcpu);
  6858. if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
  6859. vcpu->arch.pv.pv_unhalted)
  6860. mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
  6861. else
  6862. mp_state->mp_state = vcpu->arch.mp_state;
  6863. vcpu_put(vcpu);
  6864. return 0;
  6865. }
  6866. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  6867. struct kvm_mp_state *mp_state)
  6868. {
  6869. int ret = -EINVAL;
  6870. vcpu_load(vcpu);
  6871. if (!lapic_in_kernel(vcpu) &&
  6872. mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
  6873. goto out;
  6874. /* INITs are latched while in SMM */
  6875. if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
  6876. (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
  6877. mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
  6878. goto out;
  6879. if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
  6880. vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
  6881. set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
  6882. } else
  6883. vcpu->arch.mp_state = mp_state->mp_state;
  6884. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6885. ret = 0;
  6886. out:
  6887. vcpu_put(vcpu);
  6888. return ret;
  6889. }
  6890. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  6891. int reason, bool has_error_code, u32 error_code)
  6892. {
  6893. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  6894. int ret;
  6895. init_emulate_ctxt(vcpu);
  6896. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  6897. has_error_code, error_code);
  6898. if (ret)
  6899. return EMULATE_FAIL;
  6900. kvm_rip_write(vcpu, ctxt->eip);
  6901. kvm_set_rflags(vcpu, ctxt->eflags);
  6902. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6903. return EMULATE_DONE;
  6904. }
  6905. EXPORT_SYMBOL_GPL(kvm_task_switch);
  6906. static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  6907. {
  6908. if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
  6909. (sregs->cr4 & X86_CR4_OSXSAVE))
  6910. return -EINVAL;
  6911. if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
  6912. /*
  6913. * When EFER.LME and CR0.PG are set, the processor is in
  6914. * 64-bit mode (though maybe in a 32-bit code segment).
  6915. * CR4.PAE and EFER.LMA must be set.
  6916. */
  6917. if (!(sregs->cr4 & X86_CR4_PAE)
  6918. || !(sregs->efer & EFER_LMA))
  6919. return -EINVAL;
  6920. } else {
  6921. /*
  6922. * Not in 64-bit mode: EFER.LMA is clear and the code
  6923. * segment cannot be 64-bit.
  6924. */
  6925. if (sregs->efer & EFER_LMA || sregs->cs.l)
  6926. return -EINVAL;
  6927. }
  6928. return 0;
  6929. }
  6930. static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  6931. {
  6932. struct msr_data apic_base_msr;
  6933. int mmu_reset_needed = 0;
  6934. int cpuid_update_needed = 0;
  6935. int pending_vec, max_bits, idx;
  6936. struct desc_ptr dt;
  6937. int ret = -EINVAL;
  6938. if (kvm_valid_sregs(vcpu, sregs))
  6939. goto out;
  6940. apic_base_msr.data = sregs->apic_base;
  6941. apic_base_msr.host_initiated = true;
  6942. if (kvm_set_apic_base(vcpu, &apic_base_msr))
  6943. goto out;
  6944. dt.size = sregs->idt.limit;
  6945. dt.address = sregs->idt.base;
  6946. kvm_x86_ops->set_idt(vcpu, &dt);
  6947. dt.size = sregs->gdt.limit;
  6948. dt.address = sregs->gdt.base;
  6949. kvm_x86_ops->set_gdt(vcpu, &dt);
  6950. vcpu->arch.cr2 = sregs->cr2;
  6951. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  6952. vcpu->arch.cr3 = sregs->cr3;
  6953. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  6954. kvm_set_cr8(vcpu, sregs->cr8);
  6955. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  6956. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  6957. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  6958. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  6959. vcpu->arch.cr0 = sregs->cr0;
  6960. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  6961. cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
  6962. (X86_CR4_OSXSAVE | X86_CR4_PKE));
  6963. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  6964. if (cpuid_update_needed)
  6965. kvm_update_cpuid(vcpu);
  6966. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6967. if (!is_long_mode(vcpu) && is_pae(vcpu)) {
  6968. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  6969. mmu_reset_needed = 1;
  6970. }
  6971. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6972. if (mmu_reset_needed)
  6973. kvm_mmu_reset_context(vcpu);
  6974. max_bits = KVM_NR_INTERRUPTS;
  6975. pending_vec = find_first_bit(
  6976. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  6977. if (pending_vec < max_bits) {
  6978. kvm_queue_interrupt(vcpu, pending_vec, false);
  6979. pr_debug("Set back pending irq %d\n", pending_vec);
  6980. }
  6981. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  6982. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  6983. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  6984. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  6985. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  6986. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  6987. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  6988. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  6989. update_cr8_intercept(vcpu);
  6990. /* Older userspace won't unhalt the vcpu on reset. */
  6991. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  6992. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  6993. !is_protmode(vcpu))
  6994. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6995. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6996. ret = 0;
  6997. out:
  6998. return ret;
  6999. }
  7000. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  7001. struct kvm_sregs *sregs)
  7002. {
  7003. int ret;
  7004. vcpu_load(vcpu);
  7005. ret = __set_sregs(vcpu, sregs);
  7006. vcpu_put(vcpu);
  7007. return ret;
  7008. }
  7009. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  7010. struct kvm_guest_debug *dbg)
  7011. {
  7012. unsigned long rflags;
  7013. int i, r;
  7014. vcpu_load(vcpu);
  7015. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  7016. r = -EBUSY;
  7017. if (vcpu->arch.exception.pending)
  7018. goto out;
  7019. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  7020. kvm_queue_exception(vcpu, DB_VECTOR);
  7021. else
  7022. kvm_queue_exception(vcpu, BP_VECTOR);
  7023. }
  7024. /*
  7025. * Read rflags as long as potentially injected trace flags are still
  7026. * filtered out.
  7027. */
  7028. rflags = kvm_get_rflags(vcpu);
  7029. vcpu->guest_debug = dbg->control;
  7030. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  7031. vcpu->guest_debug = 0;
  7032. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  7033. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  7034. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  7035. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  7036. } else {
  7037. for (i = 0; i < KVM_NR_DB_REGS; i++)
  7038. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  7039. }
  7040. kvm_update_dr7(vcpu);
  7041. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  7042. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  7043. get_segment_base(vcpu, VCPU_SREG_CS);
  7044. /*
  7045. * Trigger an rflags update that will inject or remove the trace
  7046. * flags.
  7047. */
  7048. kvm_set_rflags(vcpu, rflags);
  7049. kvm_x86_ops->update_bp_intercept(vcpu);
  7050. r = 0;
  7051. out:
  7052. vcpu_put(vcpu);
  7053. return r;
  7054. }
  7055. /*
  7056. * Translate a guest virtual address to a guest physical address.
  7057. */
  7058. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  7059. struct kvm_translation *tr)
  7060. {
  7061. unsigned long vaddr = tr->linear_address;
  7062. gpa_t gpa;
  7063. int idx;
  7064. vcpu_load(vcpu);
  7065. idx = srcu_read_lock(&vcpu->kvm->srcu);
  7066. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  7067. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  7068. tr->physical_address = gpa;
  7069. tr->valid = gpa != UNMAPPED_GVA;
  7070. tr->writeable = 1;
  7071. tr->usermode = 0;
  7072. vcpu_put(vcpu);
  7073. return 0;
  7074. }
  7075. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  7076. {
  7077. struct fxregs_state *fxsave;
  7078. vcpu_load(vcpu);
  7079. fxsave = &vcpu->arch.guest_fpu.state.fxsave;
  7080. memcpy(fpu->fpr, fxsave->st_space, 128);
  7081. fpu->fcw = fxsave->cwd;
  7082. fpu->fsw = fxsave->swd;
  7083. fpu->ftwx = fxsave->twd;
  7084. fpu->last_opcode = fxsave->fop;
  7085. fpu->last_ip = fxsave->rip;
  7086. fpu->last_dp = fxsave->rdp;
  7087. memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
  7088. vcpu_put(vcpu);
  7089. return 0;
  7090. }
  7091. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  7092. {
  7093. struct fxregs_state *fxsave;
  7094. vcpu_load(vcpu);
  7095. fxsave = &vcpu->arch.guest_fpu.state.fxsave;
  7096. memcpy(fxsave->st_space, fpu->fpr, 128);
  7097. fxsave->cwd = fpu->fcw;
  7098. fxsave->swd = fpu->fsw;
  7099. fxsave->twd = fpu->ftwx;
  7100. fxsave->fop = fpu->last_opcode;
  7101. fxsave->rip = fpu->last_ip;
  7102. fxsave->rdp = fpu->last_dp;
  7103. memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
  7104. vcpu_put(vcpu);
  7105. return 0;
  7106. }
  7107. static void store_regs(struct kvm_vcpu *vcpu)
  7108. {
  7109. BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
  7110. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
  7111. __get_regs(vcpu, &vcpu->run->s.regs.regs);
  7112. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
  7113. __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
  7114. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
  7115. kvm_vcpu_ioctl_x86_get_vcpu_events(
  7116. vcpu, &vcpu->run->s.regs.events);
  7117. }
  7118. static int sync_regs(struct kvm_vcpu *vcpu)
  7119. {
  7120. if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
  7121. return -EINVAL;
  7122. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
  7123. __set_regs(vcpu, &vcpu->run->s.regs.regs);
  7124. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
  7125. }
  7126. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
  7127. if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
  7128. return -EINVAL;
  7129. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
  7130. }
  7131. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
  7132. if (kvm_vcpu_ioctl_x86_set_vcpu_events(
  7133. vcpu, &vcpu->run->s.regs.events))
  7134. return -EINVAL;
  7135. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
  7136. }
  7137. return 0;
  7138. }
  7139. static void fx_init(struct kvm_vcpu *vcpu)
  7140. {
  7141. fpstate_init(&vcpu->arch.guest_fpu.state);
  7142. if (boot_cpu_has(X86_FEATURE_XSAVES))
  7143. vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
  7144. host_xcr0 | XSTATE_COMPACTION_ENABLED;
  7145. /*
  7146. * Ensure guest xcr0 is valid for loading
  7147. */
  7148. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  7149. vcpu->arch.cr0 |= X86_CR0_ET;
  7150. }
  7151. /* Swap (qemu) user FPU context for the guest FPU context. */
  7152. void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  7153. {
  7154. preempt_disable();
  7155. copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
  7156. /* PKRU is separately restored in kvm_x86_ops->run. */
  7157. __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
  7158. ~XFEATURE_MASK_PKRU);
  7159. preempt_enable();
  7160. trace_kvm_fpu(1);
  7161. }
  7162. /* When vcpu_run ends, restore user space FPU context. */
  7163. void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  7164. {
  7165. preempt_disable();
  7166. copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
  7167. copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
  7168. preempt_enable();
  7169. ++vcpu->stat.fpu_reload;
  7170. trace_kvm_fpu(0);
  7171. }
  7172. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  7173. {
  7174. void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
  7175. kvmclock_reset(vcpu);
  7176. kvm_x86_ops->vcpu_free(vcpu);
  7177. free_cpumask_var(wbinvd_dirty_mask);
  7178. }
  7179. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  7180. unsigned int id)
  7181. {
  7182. struct kvm_vcpu *vcpu;
  7183. if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  7184. printk_once(KERN_WARNING
  7185. "kvm: SMP vm created on host with unstable TSC; "
  7186. "guest TSC will not be reliable\n");
  7187. vcpu = kvm_x86_ops->vcpu_create(kvm, id);
  7188. return vcpu;
  7189. }
  7190. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  7191. {
  7192. kvm_vcpu_mtrr_init(vcpu);
  7193. vcpu_load(vcpu);
  7194. kvm_vcpu_reset(vcpu, false);
  7195. kvm_mmu_setup(vcpu);
  7196. vcpu_put(vcpu);
  7197. return 0;
  7198. }
  7199. void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  7200. {
  7201. struct msr_data msr;
  7202. struct kvm *kvm = vcpu->kvm;
  7203. kvm_hv_vcpu_postcreate(vcpu);
  7204. if (mutex_lock_killable(&vcpu->mutex))
  7205. return;
  7206. vcpu_load(vcpu);
  7207. msr.data = 0x0;
  7208. msr.index = MSR_IA32_TSC;
  7209. msr.host_initiated = true;
  7210. kvm_write_tsc(vcpu, &msr);
  7211. vcpu_put(vcpu);
  7212. mutex_unlock(&vcpu->mutex);
  7213. if (!kvmclock_periodic_sync)
  7214. return;
  7215. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  7216. KVMCLOCK_SYNC_PERIOD);
  7217. }
  7218. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  7219. {
  7220. vcpu->arch.apf.msr_val = 0;
  7221. vcpu_load(vcpu);
  7222. kvm_mmu_unload(vcpu);
  7223. vcpu_put(vcpu);
  7224. kvm_x86_ops->vcpu_free(vcpu);
  7225. }
  7226. void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  7227. {
  7228. kvm_lapic_reset(vcpu, init_event);
  7229. vcpu->arch.hflags = 0;
  7230. vcpu->arch.smi_pending = 0;
  7231. vcpu->arch.smi_count = 0;
  7232. atomic_set(&vcpu->arch.nmi_queued, 0);
  7233. vcpu->arch.nmi_pending = 0;
  7234. vcpu->arch.nmi_injected = false;
  7235. kvm_clear_interrupt_queue(vcpu);
  7236. kvm_clear_exception_queue(vcpu);
  7237. vcpu->arch.exception.pending = false;
  7238. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  7239. kvm_update_dr0123(vcpu);
  7240. vcpu->arch.dr6 = DR6_INIT;
  7241. kvm_update_dr6(vcpu);
  7242. vcpu->arch.dr7 = DR7_FIXED_1;
  7243. kvm_update_dr7(vcpu);
  7244. vcpu->arch.cr2 = 0;
  7245. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7246. vcpu->arch.apf.msr_val = 0;
  7247. vcpu->arch.st.msr_val = 0;
  7248. kvmclock_reset(vcpu);
  7249. kvm_clear_async_pf_completion_queue(vcpu);
  7250. kvm_async_pf_hash_reset(vcpu);
  7251. vcpu->arch.apf.halted = false;
  7252. if (kvm_mpx_supported()) {
  7253. void *mpx_state_buffer;
  7254. /*
  7255. * To avoid have the INIT path from kvm_apic_has_events() that be
  7256. * called with loaded FPU and does not let userspace fix the state.
  7257. */
  7258. if (init_event)
  7259. kvm_put_guest_fpu(vcpu);
  7260. mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
  7261. XFEATURE_MASK_BNDREGS);
  7262. if (mpx_state_buffer)
  7263. memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
  7264. mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
  7265. XFEATURE_MASK_BNDCSR);
  7266. if (mpx_state_buffer)
  7267. memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
  7268. if (init_event)
  7269. kvm_load_guest_fpu(vcpu);
  7270. }
  7271. if (!init_event) {
  7272. kvm_pmu_reset(vcpu);
  7273. vcpu->arch.smbase = 0x30000;
  7274. vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
  7275. vcpu->arch.msr_misc_features_enables = 0;
  7276. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  7277. }
  7278. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  7279. vcpu->arch.regs_avail = ~0;
  7280. vcpu->arch.regs_dirty = ~0;
  7281. vcpu->arch.ia32_xss = 0;
  7282. kvm_x86_ops->vcpu_reset(vcpu, init_event);
  7283. }
  7284. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  7285. {
  7286. struct kvm_segment cs;
  7287. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  7288. cs.selector = vector << 8;
  7289. cs.base = vector << 12;
  7290. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  7291. kvm_rip_write(vcpu, 0);
  7292. }
  7293. int kvm_arch_hardware_enable(void)
  7294. {
  7295. struct kvm *kvm;
  7296. struct kvm_vcpu *vcpu;
  7297. int i;
  7298. int ret;
  7299. u64 local_tsc;
  7300. u64 max_tsc = 0;
  7301. bool stable, backwards_tsc = false;
  7302. kvm_shared_msr_cpu_online();
  7303. ret = kvm_x86_ops->hardware_enable();
  7304. if (ret != 0)
  7305. return ret;
  7306. local_tsc = rdtsc();
  7307. stable = !kvm_check_tsc_unstable();
  7308. list_for_each_entry(kvm, &vm_list, vm_list) {
  7309. kvm_for_each_vcpu(i, vcpu, kvm) {
  7310. if (!stable && vcpu->cpu == smp_processor_id())
  7311. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  7312. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  7313. backwards_tsc = true;
  7314. if (vcpu->arch.last_host_tsc > max_tsc)
  7315. max_tsc = vcpu->arch.last_host_tsc;
  7316. }
  7317. }
  7318. }
  7319. /*
  7320. * Sometimes, even reliable TSCs go backwards. This happens on
  7321. * platforms that reset TSC during suspend or hibernate actions, but
  7322. * maintain synchronization. We must compensate. Fortunately, we can
  7323. * detect that condition here, which happens early in CPU bringup,
  7324. * before any KVM threads can be running. Unfortunately, we can't
  7325. * bring the TSCs fully up to date with real time, as we aren't yet far
  7326. * enough into CPU bringup that we know how much real time has actually
  7327. * elapsed; our helper function, ktime_get_boot_ns() will be using boot
  7328. * variables that haven't been updated yet.
  7329. *
  7330. * So we simply find the maximum observed TSC above, then record the
  7331. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  7332. * the adjustment will be applied. Note that we accumulate
  7333. * adjustments, in case multiple suspend cycles happen before some VCPU
  7334. * gets a chance to run again. In the event that no KVM threads get a
  7335. * chance to run, we will miss the entire elapsed period, as we'll have
  7336. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  7337. * loose cycle time. This isn't too big a deal, since the loss will be
  7338. * uniform across all VCPUs (not to mention the scenario is extremely
  7339. * unlikely). It is possible that a second hibernate recovery happens
  7340. * much faster than a first, causing the observed TSC here to be
  7341. * smaller; this would require additional padding adjustment, which is
  7342. * why we set last_host_tsc to the local tsc observed here.
  7343. *
  7344. * N.B. - this code below runs only on platforms with reliable TSC,
  7345. * as that is the only way backwards_tsc is set above. Also note
  7346. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  7347. * have the same delta_cyc adjustment applied if backwards_tsc
  7348. * is detected. Note further, this adjustment is only done once,
  7349. * as we reset last_host_tsc on all VCPUs to stop this from being
  7350. * called multiple times (one for each physical CPU bringup).
  7351. *
  7352. * Platforms with unreliable TSCs don't have to deal with this, they
  7353. * will be compensated by the logic in vcpu_load, which sets the TSC to
  7354. * catchup mode. This will catchup all VCPUs to real time, but cannot
  7355. * guarantee that they stay in perfect synchronization.
  7356. */
  7357. if (backwards_tsc) {
  7358. u64 delta_cyc = max_tsc - local_tsc;
  7359. list_for_each_entry(kvm, &vm_list, vm_list) {
  7360. kvm->arch.backwards_tsc_observed = true;
  7361. kvm_for_each_vcpu(i, vcpu, kvm) {
  7362. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  7363. vcpu->arch.last_host_tsc = local_tsc;
  7364. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  7365. }
  7366. /*
  7367. * We have to disable TSC offset matching.. if you were
  7368. * booting a VM while issuing an S4 host suspend....
  7369. * you may have some problem. Solving this issue is
  7370. * left as an exercise to the reader.
  7371. */
  7372. kvm->arch.last_tsc_nsec = 0;
  7373. kvm->arch.last_tsc_write = 0;
  7374. }
  7375. }
  7376. return 0;
  7377. }
  7378. void kvm_arch_hardware_disable(void)
  7379. {
  7380. kvm_x86_ops->hardware_disable();
  7381. drop_user_return_notifiers();
  7382. }
  7383. int kvm_arch_hardware_setup(void)
  7384. {
  7385. int r;
  7386. r = kvm_x86_ops->hardware_setup();
  7387. if (r != 0)
  7388. return r;
  7389. if (kvm_has_tsc_control) {
  7390. /*
  7391. * Make sure the user can only configure tsc_khz values that
  7392. * fit into a signed integer.
  7393. * A min value is not calculated because it will always
  7394. * be 1 on all machines.
  7395. */
  7396. u64 max = min(0x7fffffffULL,
  7397. __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
  7398. kvm_max_guest_tsc_khz = max;
  7399. kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
  7400. }
  7401. kvm_init_msr_list();
  7402. return 0;
  7403. }
  7404. void kvm_arch_hardware_unsetup(void)
  7405. {
  7406. kvm_x86_ops->hardware_unsetup();
  7407. }
  7408. void kvm_arch_check_processor_compat(void *rtn)
  7409. {
  7410. kvm_x86_ops->check_processor_compatibility(rtn);
  7411. }
  7412. bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
  7413. {
  7414. return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
  7415. }
  7416. EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
  7417. bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
  7418. {
  7419. return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
  7420. }
  7421. struct static_key kvm_no_apic_vcpu __read_mostly;
  7422. EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
  7423. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  7424. {
  7425. struct page *page;
  7426. int r;
  7427. vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
  7428. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  7429. if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
  7430. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  7431. else
  7432. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  7433. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  7434. if (!page) {
  7435. r = -ENOMEM;
  7436. goto fail;
  7437. }
  7438. vcpu->arch.pio_data = page_address(page);
  7439. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  7440. r = kvm_mmu_create(vcpu);
  7441. if (r < 0)
  7442. goto fail_free_pio_data;
  7443. if (irqchip_in_kernel(vcpu->kvm)) {
  7444. r = kvm_create_lapic(vcpu);
  7445. if (r < 0)
  7446. goto fail_mmu_destroy;
  7447. } else
  7448. static_key_slow_inc(&kvm_no_apic_vcpu);
  7449. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  7450. GFP_KERNEL);
  7451. if (!vcpu->arch.mce_banks) {
  7452. r = -ENOMEM;
  7453. goto fail_free_lapic;
  7454. }
  7455. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  7456. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
  7457. r = -ENOMEM;
  7458. goto fail_free_mce_banks;
  7459. }
  7460. fx_init(vcpu);
  7461. vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
  7462. vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
  7463. vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
  7464. kvm_async_pf_hash_reset(vcpu);
  7465. kvm_pmu_init(vcpu);
  7466. vcpu->arch.pending_external_vector = -1;
  7467. vcpu->arch.preempted_in_kernel = false;
  7468. kvm_hv_vcpu_init(vcpu);
  7469. return 0;
  7470. fail_free_mce_banks:
  7471. kfree(vcpu->arch.mce_banks);
  7472. fail_free_lapic:
  7473. kvm_free_lapic(vcpu);
  7474. fail_mmu_destroy:
  7475. kvm_mmu_destroy(vcpu);
  7476. fail_free_pio_data:
  7477. free_page((unsigned long)vcpu->arch.pio_data);
  7478. fail:
  7479. return r;
  7480. }
  7481. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  7482. {
  7483. int idx;
  7484. kvm_hv_vcpu_uninit(vcpu);
  7485. kvm_pmu_destroy(vcpu);
  7486. kfree(vcpu->arch.mce_banks);
  7487. kvm_free_lapic(vcpu);
  7488. idx = srcu_read_lock(&vcpu->kvm->srcu);
  7489. kvm_mmu_destroy(vcpu);
  7490. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  7491. free_page((unsigned long)vcpu->arch.pio_data);
  7492. if (!lapic_in_kernel(vcpu))
  7493. static_key_slow_dec(&kvm_no_apic_vcpu);
  7494. }
  7495. void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  7496. {
  7497. kvm_x86_ops->sched_in(vcpu, cpu);
  7498. }
  7499. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  7500. {
  7501. if (type)
  7502. return -EINVAL;
  7503. INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
  7504. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  7505. INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
  7506. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  7507. atomic_set(&kvm->arch.noncoherent_dma_count, 0);
  7508. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  7509. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  7510. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  7511. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  7512. &kvm->arch.irq_sources_bitmap);
  7513. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  7514. mutex_init(&kvm->arch.apic_map_lock);
  7515. spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
  7516. kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
  7517. pvclock_update_vm_gtod_copy(kvm);
  7518. INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
  7519. INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
  7520. kvm_hv_init_vm(kvm);
  7521. kvm_page_track_init(kvm);
  7522. kvm_mmu_init_vm(kvm);
  7523. if (kvm_x86_ops->vm_init)
  7524. return kvm_x86_ops->vm_init(kvm);
  7525. return 0;
  7526. }
  7527. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  7528. {
  7529. vcpu_load(vcpu);
  7530. kvm_mmu_unload(vcpu);
  7531. vcpu_put(vcpu);
  7532. }
  7533. static void kvm_free_vcpus(struct kvm *kvm)
  7534. {
  7535. unsigned int i;
  7536. struct kvm_vcpu *vcpu;
  7537. /*
  7538. * Unpin any mmu pages first.
  7539. */
  7540. kvm_for_each_vcpu(i, vcpu, kvm) {
  7541. kvm_clear_async_pf_completion_queue(vcpu);
  7542. kvm_unload_vcpu_mmu(vcpu);
  7543. }
  7544. kvm_for_each_vcpu(i, vcpu, kvm)
  7545. kvm_arch_vcpu_free(vcpu);
  7546. mutex_lock(&kvm->lock);
  7547. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  7548. kvm->vcpus[i] = NULL;
  7549. atomic_set(&kvm->online_vcpus, 0);
  7550. mutex_unlock(&kvm->lock);
  7551. }
  7552. void kvm_arch_sync_events(struct kvm *kvm)
  7553. {
  7554. cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
  7555. cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
  7556. kvm_free_pit(kvm);
  7557. }
  7558. int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  7559. {
  7560. int i, r;
  7561. unsigned long hva;
  7562. struct kvm_memslots *slots = kvm_memslots(kvm);
  7563. struct kvm_memory_slot *slot, old;
  7564. /* Called with kvm->slots_lock held. */
  7565. if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
  7566. return -EINVAL;
  7567. slot = id_to_memslot(slots, id);
  7568. if (size) {
  7569. if (slot->npages)
  7570. return -EEXIST;
  7571. /*
  7572. * MAP_SHARED to prevent internal slot pages from being moved
  7573. * by fork()/COW.
  7574. */
  7575. hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
  7576. MAP_SHARED | MAP_ANONYMOUS, 0);
  7577. if (IS_ERR((void *)hva))
  7578. return PTR_ERR((void *)hva);
  7579. } else {
  7580. if (!slot->npages)
  7581. return 0;
  7582. hva = 0;
  7583. }
  7584. old = *slot;
  7585. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  7586. struct kvm_userspace_memory_region m;
  7587. m.slot = id | (i << 16);
  7588. m.flags = 0;
  7589. m.guest_phys_addr = gpa;
  7590. m.userspace_addr = hva;
  7591. m.memory_size = size;
  7592. r = __kvm_set_memory_region(kvm, &m);
  7593. if (r < 0)
  7594. return r;
  7595. }
  7596. if (!size)
  7597. vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
  7598. return 0;
  7599. }
  7600. EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  7601. int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  7602. {
  7603. int r;
  7604. mutex_lock(&kvm->slots_lock);
  7605. r = __x86_set_memory_region(kvm, id, gpa, size);
  7606. mutex_unlock(&kvm->slots_lock);
  7607. return r;
  7608. }
  7609. EXPORT_SYMBOL_GPL(x86_set_memory_region);
  7610. void kvm_arch_destroy_vm(struct kvm *kvm)
  7611. {
  7612. if (current->mm == kvm->mm) {
  7613. /*
  7614. * Free memory regions allocated on behalf of userspace,
  7615. * unless the the memory map has changed due to process exit
  7616. * or fd copying.
  7617. */
  7618. x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
  7619. x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
  7620. x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
  7621. }
  7622. if (kvm_x86_ops->vm_destroy)
  7623. kvm_x86_ops->vm_destroy(kvm);
  7624. kvm_pic_destroy(kvm);
  7625. kvm_ioapic_destroy(kvm);
  7626. kvm_free_vcpus(kvm);
  7627. kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  7628. kvm_mmu_uninit_vm(kvm);
  7629. kvm_page_track_cleanup(kvm);
  7630. kvm_hv_destroy_vm(kvm);
  7631. }
  7632. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
  7633. struct kvm_memory_slot *dont)
  7634. {
  7635. int i;
  7636. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7637. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  7638. kvfree(free->arch.rmap[i]);
  7639. free->arch.rmap[i] = NULL;
  7640. }
  7641. if (i == 0)
  7642. continue;
  7643. if (!dont || free->arch.lpage_info[i - 1] !=
  7644. dont->arch.lpage_info[i - 1]) {
  7645. kvfree(free->arch.lpage_info[i - 1]);
  7646. free->arch.lpage_info[i - 1] = NULL;
  7647. }
  7648. }
  7649. kvm_page_track_free_memslot(free, dont);
  7650. }
  7651. int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
  7652. unsigned long npages)
  7653. {
  7654. int i;
  7655. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7656. struct kvm_lpage_info *linfo;
  7657. unsigned long ugfn;
  7658. int lpages;
  7659. int level = i + 1;
  7660. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  7661. slot->base_gfn, level) + 1;
  7662. slot->arch.rmap[i] =
  7663. kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
  7664. GFP_KERNEL);
  7665. if (!slot->arch.rmap[i])
  7666. goto out_free;
  7667. if (i == 0)
  7668. continue;
  7669. linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL);
  7670. if (!linfo)
  7671. goto out_free;
  7672. slot->arch.lpage_info[i - 1] = linfo;
  7673. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  7674. linfo[0].disallow_lpage = 1;
  7675. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  7676. linfo[lpages - 1].disallow_lpage = 1;
  7677. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  7678. /*
  7679. * If the gfn and userspace address are not aligned wrt each
  7680. * other, or if explicitly asked to, disable large page
  7681. * support for this slot
  7682. */
  7683. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  7684. !kvm_largepages_enabled()) {
  7685. unsigned long j;
  7686. for (j = 0; j < lpages; ++j)
  7687. linfo[j].disallow_lpage = 1;
  7688. }
  7689. }
  7690. if (kvm_page_track_create_memslot(slot, npages))
  7691. goto out_free;
  7692. return 0;
  7693. out_free:
  7694. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7695. kvfree(slot->arch.rmap[i]);
  7696. slot->arch.rmap[i] = NULL;
  7697. if (i == 0)
  7698. continue;
  7699. kvfree(slot->arch.lpage_info[i - 1]);
  7700. slot->arch.lpage_info[i - 1] = NULL;
  7701. }
  7702. return -ENOMEM;
  7703. }
  7704. void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
  7705. {
  7706. /*
  7707. * memslots->generation has been incremented.
  7708. * mmio generation may have reached its maximum value.
  7709. */
  7710. kvm_mmu_invalidate_mmio_sptes(kvm, slots);
  7711. }
  7712. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  7713. struct kvm_memory_slot *memslot,
  7714. const struct kvm_userspace_memory_region *mem,
  7715. enum kvm_mr_change change)
  7716. {
  7717. return 0;
  7718. }
  7719. static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
  7720. struct kvm_memory_slot *new)
  7721. {
  7722. /* Still write protect RO slot */
  7723. if (new->flags & KVM_MEM_READONLY) {
  7724. kvm_mmu_slot_remove_write_access(kvm, new);
  7725. return;
  7726. }
  7727. /*
  7728. * Call kvm_x86_ops dirty logging hooks when they are valid.
  7729. *
  7730. * kvm_x86_ops->slot_disable_log_dirty is called when:
  7731. *
  7732. * - KVM_MR_CREATE with dirty logging is disabled
  7733. * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
  7734. *
  7735. * The reason is, in case of PML, we need to set D-bit for any slots
  7736. * with dirty logging disabled in order to eliminate unnecessary GPA
  7737. * logging in PML buffer (and potential PML buffer full VMEXT). This
  7738. * guarantees leaving PML enabled during guest's lifetime won't have
  7739. * any additonal overhead from PML when guest is running with dirty
  7740. * logging disabled for memory slots.
  7741. *
  7742. * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
  7743. * to dirty logging mode.
  7744. *
  7745. * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
  7746. *
  7747. * In case of write protect:
  7748. *
  7749. * Write protect all pages for dirty logging.
  7750. *
  7751. * All the sptes including the large sptes which point to this
  7752. * slot are set to readonly. We can not create any new large
  7753. * spte on this slot until the end of the logging.
  7754. *
  7755. * See the comments in fast_page_fault().
  7756. */
  7757. if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  7758. if (kvm_x86_ops->slot_enable_log_dirty)
  7759. kvm_x86_ops->slot_enable_log_dirty(kvm, new);
  7760. else
  7761. kvm_mmu_slot_remove_write_access(kvm, new);
  7762. } else {
  7763. if (kvm_x86_ops->slot_disable_log_dirty)
  7764. kvm_x86_ops->slot_disable_log_dirty(kvm, new);
  7765. }
  7766. }
  7767. void kvm_arch_commit_memory_region(struct kvm *kvm,
  7768. const struct kvm_userspace_memory_region *mem,
  7769. const struct kvm_memory_slot *old,
  7770. const struct kvm_memory_slot *new,
  7771. enum kvm_mr_change change)
  7772. {
  7773. int nr_mmu_pages = 0;
  7774. if (!kvm->arch.n_requested_mmu_pages)
  7775. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  7776. if (nr_mmu_pages)
  7777. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  7778. /*
  7779. * Dirty logging tracks sptes in 4k granularity, meaning that large
  7780. * sptes have to be split. If live migration is successful, the guest
  7781. * in the source machine will be destroyed and large sptes will be
  7782. * created in the destination. However, if the guest continues to run
  7783. * in the source machine (for example if live migration fails), small
  7784. * sptes will remain around and cause bad performance.
  7785. *
  7786. * Scan sptes if dirty logging has been stopped, dropping those
  7787. * which can be collapsed into a single large-page spte. Later
  7788. * page faults will create the large-page sptes.
  7789. */
  7790. if ((change != KVM_MR_DELETE) &&
  7791. (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
  7792. !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
  7793. kvm_mmu_zap_collapsible_sptes(kvm, new);
  7794. /*
  7795. * Set up write protection and/or dirty logging for the new slot.
  7796. *
  7797. * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
  7798. * been zapped so no dirty logging staff is needed for old slot. For
  7799. * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
  7800. * new and it's also covered when dealing with the new slot.
  7801. *
  7802. * FIXME: const-ify all uses of struct kvm_memory_slot.
  7803. */
  7804. if (change != KVM_MR_DELETE)
  7805. kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
  7806. }
  7807. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  7808. {
  7809. kvm_mmu_invalidate_zap_all_pages(kvm);
  7810. }
  7811. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  7812. struct kvm_memory_slot *slot)
  7813. {
  7814. kvm_page_track_flush_slot(kvm, slot);
  7815. }
  7816. static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
  7817. {
  7818. if (!list_empty_careful(&vcpu->async_pf.done))
  7819. return true;
  7820. if (kvm_apic_has_events(vcpu))
  7821. return true;
  7822. if (vcpu->arch.pv.pv_unhalted)
  7823. return true;
  7824. if (vcpu->arch.exception.pending)
  7825. return true;
  7826. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  7827. (vcpu->arch.nmi_pending &&
  7828. kvm_x86_ops->nmi_allowed(vcpu)))
  7829. return true;
  7830. if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
  7831. (vcpu->arch.smi_pending && !is_smm(vcpu)))
  7832. return true;
  7833. if (kvm_arch_interrupt_allowed(vcpu) &&
  7834. kvm_cpu_has_interrupt(vcpu))
  7835. return true;
  7836. if (kvm_hv_has_stimer_pending(vcpu))
  7837. return true;
  7838. return false;
  7839. }
  7840. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  7841. {
  7842. return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
  7843. }
  7844. bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
  7845. {
  7846. return vcpu->arch.preempted_in_kernel;
  7847. }
  7848. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  7849. {
  7850. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  7851. }
  7852. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  7853. {
  7854. return kvm_x86_ops->interrupt_allowed(vcpu);
  7855. }
  7856. unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
  7857. {
  7858. if (is_64_bit_mode(vcpu))
  7859. return kvm_rip_read(vcpu);
  7860. return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
  7861. kvm_rip_read(vcpu));
  7862. }
  7863. EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
  7864. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  7865. {
  7866. return kvm_get_linear_rip(vcpu) == linear_rip;
  7867. }
  7868. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  7869. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  7870. {
  7871. unsigned long rflags;
  7872. rflags = kvm_x86_ops->get_rflags(vcpu);
  7873. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  7874. rflags &= ~X86_EFLAGS_TF;
  7875. return rflags;
  7876. }
  7877. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  7878. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7879. {
  7880. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  7881. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  7882. rflags |= X86_EFLAGS_TF;
  7883. kvm_x86_ops->set_rflags(vcpu, rflags);
  7884. }
  7885. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7886. {
  7887. __kvm_set_rflags(vcpu, rflags);
  7888. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7889. }
  7890. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  7891. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  7892. {
  7893. int r;
  7894. if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
  7895. work->wakeup_all)
  7896. return;
  7897. r = kvm_mmu_reload(vcpu);
  7898. if (unlikely(r))
  7899. return;
  7900. if (!vcpu->arch.mmu.direct_map &&
  7901. work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  7902. return;
  7903. vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  7904. }
  7905. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  7906. {
  7907. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  7908. }
  7909. static inline u32 kvm_async_pf_next_probe(u32 key)
  7910. {
  7911. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  7912. }
  7913. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7914. {
  7915. u32 key = kvm_async_pf_hash_fn(gfn);
  7916. while (vcpu->arch.apf.gfns[key] != ~0)
  7917. key = kvm_async_pf_next_probe(key);
  7918. vcpu->arch.apf.gfns[key] = gfn;
  7919. }
  7920. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  7921. {
  7922. int i;
  7923. u32 key = kvm_async_pf_hash_fn(gfn);
  7924. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  7925. (vcpu->arch.apf.gfns[key] != gfn &&
  7926. vcpu->arch.apf.gfns[key] != ~0); i++)
  7927. key = kvm_async_pf_next_probe(key);
  7928. return key;
  7929. }
  7930. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7931. {
  7932. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  7933. }
  7934. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7935. {
  7936. u32 i, j, k;
  7937. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  7938. while (true) {
  7939. vcpu->arch.apf.gfns[i] = ~0;
  7940. do {
  7941. j = kvm_async_pf_next_probe(j);
  7942. if (vcpu->arch.apf.gfns[j] == ~0)
  7943. return;
  7944. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  7945. /*
  7946. * k lies cyclically in ]i,j]
  7947. * | i.k.j |
  7948. * |....j i.k.| or |.k..j i...|
  7949. */
  7950. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  7951. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  7952. i = j;
  7953. }
  7954. }
  7955. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  7956. {
  7957. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  7958. sizeof(val));
  7959. }
  7960. static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
  7961. {
  7962. return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
  7963. sizeof(u32));
  7964. }
  7965. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  7966. struct kvm_async_pf *work)
  7967. {
  7968. struct x86_exception fault;
  7969. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  7970. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  7971. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  7972. (vcpu->arch.apf.send_user_only &&
  7973. kvm_x86_ops->get_cpl(vcpu) == 0))
  7974. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  7975. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  7976. fault.vector = PF_VECTOR;
  7977. fault.error_code_valid = true;
  7978. fault.error_code = 0;
  7979. fault.nested_page_fault = false;
  7980. fault.address = work->arch.token;
  7981. fault.async_page_fault = true;
  7982. kvm_inject_page_fault(vcpu, &fault);
  7983. }
  7984. }
  7985. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  7986. struct kvm_async_pf *work)
  7987. {
  7988. struct x86_exception fault;
  7989. u32 val;
  7990. if (work->wakeup_all)
  7991. work->arch.token = ~0; /* broadcast wakeup */
  7992. else
  7993. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  7994. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  7995. if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
  7996. !apf_get_user(vcpu, &val)) {
  7997. if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
  7998. vcpu->arch.exception.pending &&
  7999. vcpu->arch.exception.nr == PF_VECTOR &&
  8000. !apf_put_user(vcpu, 0)) {
  8001. vcpu->arch.exception.injected = false;
  8002. vcpu->arch.exception.pending = false;
  8003. vcpu->arch.exception.nr = 0;
  8004. vcpu->arch.exception.has_error_code = false;
  8005. vcpu->arch.exception.error_code = 0;
  8006. } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  8007. fault.vector = PF_VECTOR;
  8008. fault.error_code_valid = true;
  8009. fault.error_code = 0;
  8010. fault.nested_page_fault = false;
  8011. fault.address = work->arch.token;
  8012. fault.async_page_fault = true;
  8013. kvm_inject_page_fault(vcpu, &fault);
  8014. }
  8015. }
  8016. vcpu->arch.apf.halted = false;
  8017. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  8018. }
  8019. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  8020. {
  8021. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  8022. return true;
  8023. else
  8024. return kvm_can_do_async_pf(vcpu);
  8025. }
  8026. void kvm_arch_start_assignment(struct kvm *kvm)
  8027. {
  8028. atomic_inc(&kvm->arch.assigned_device_count);
  8029. }
  8030. EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
  8031. void kvm_arch_end_assignment(struct kvm *kvm)
  8032. {
  8033. atomic_dec(&kvm->arch.assigned_device_count);
  8034. }
  8035. EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
  8036. bool kvm_arch_has_assigned_device(struct kvm *kvm)
  8037. {
  8038. return atomic_read(&kvm->arch.assigned_device_count);
  8039. }
  8040. EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
  8041. void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
  8042. {
  8043. atomic_inc(&kvm->arch.noncoherent_dma_count);
  8044. }
  8045. EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
  8046. void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
  8047. {
  8048. atomic_dec(&kvm->arch.noncoherent_dma_count);
  8049. }
  8050. EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
  8051. bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
  8052. {
  8053. return atomic_read(&kvm->arch.noncoherent_dma_count);
  8054. }
  8055. EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
  8056. bool kvm_arch_has_irq_bypass(void)
  8057. {
  8058. return kvm_x86_ops->update_pi_irte != NULL;
  8059. }
  8060. int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
  8061. struct irq_bypass_producer *prod)
  8062. {
  8063. struct kvm_kernel_irqfd *irqfd =
  8064. container_of(cons, struct kvm_kernel_irqfd, consumer);
  8065. irqfd->producer = prod;
  8066. return kvm_x86_ops->update_pi_irte(irqfd->kvm,
  8067. prod->irq, irqfd->gsi, 1);
  8068. }
  8069. void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
  8070. struct irq_bypass_producer *prod)
  8071. {
  8072. int ret;
  8073. struct kvm_kernel_irqfd *irqfd =
  8074. container_of(cons, struct kvm_kernel_irqfd, consumer);
  8075. WARN_ON(irqfd->producer != prod);
  8076. irqfd->producer = NULL;
  8077. /*
  8078. * When producer of consumer is unregistered, we change back to
  8079. * remapped mode, so we can re-use the current implementation
  8080. * when the irq is masked/disabled or the consumer side (KVM
  8081. * int this case doesn't want to receive the interrupts.
  8082. */
  8083. ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
  8084. if (ret)
  8085. printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
  8086. " fails: %d\n", irqfd->consumer.token, ret);
  8087. }
  8088. int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
  8089. uint32_t guest_irq, bool set)
  8090. {
  8091. if (!kvm_x86_ops->update_pi_irte)
  8092. return -EINVAL;
  8093. return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
  8094. }
  8095. bool kvm_vector_hashing_enabled(void)
  8096. {
  8097. return vector_hashing;
  8098. }
  8099. EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
  8100. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  8101. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
  8102. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  8103. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  8104. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  8105. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  8106. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  8107. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  8108. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  8109. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  8110. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  8111. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  8112. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
  8113. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
  8114. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
  8115. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
  8116. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
  8117. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
  8118. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);