x86.c 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783
  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 <linux/clocksource.h>
  30. #include <linux/interrupt.h>
  31. #include <linux/kvm.h>
  32. #include <linux/fs.h>
  33. #include <linux/vmalloc.h>
  34. #include <linux/module.h>
  35. #include <linux/mman.h>
  36. #include <linux/highmem.h>
  37. #include <linux/iommu.h>
  38. #include <linux/intel-iommu.h>
  39. #include <linux/cpufreq.h>
  40. #include <linux/user-return-notifier.h>
  41. #include <linux/srcu.h>
  42. #include <linux/slab.h>
  43. #include <linux/perf_event.h>
  44. #include <linux/uaccess.h>
  45. #include <linux/hash.h>
  46. #include <linux/pci.h>
  47. #include <linux/timekeeper_internal.h>
  48. #include <linux/pvclock_gtod.h>
  49. #include <trace/events/kvm.h>
  50. #define CREATE_TRACE_POINTS
  51. #include "trace.h"
  52. #include <asm/debugreg.h>
  53. #include <asm/msr.h>
  54. #include <asm/desc.h>
  55. #include <asm/mtrr.h>
  56. #include <asm/mce.h>
  57. #include <asm/i387.h>
  58. #include <asm/fpu-internal.h> /* Ugh! */
  59. #include <asm/xcr.h>
  60. #include <asm/pvclock.h>
  61. #include <asm/div64.h>
  62. #define MAX_IO_MSRS 256
  63. #define KVM_MAX_MCE_BANKS 32
  64. #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
  65. #define emul_to_vcpu(ctxt) \
  66. container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
  67. /* EFER defaults:
  68. * - enable syscall per default because its emulated by KVM
  69. * - enable LME and LMA per default on 64 bit KVM
  70. */
  71. #ifdef CONFIG_X86_64
  72. static
  73. u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
  74. #else
  75. static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  76. #endif
  77. #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
  78. #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
  79. static void update_cr8_intercept(struct kvm_vcpu *vcpu);
  80. static void process_nmi(struct kvm_vcpu *vcpu);
  81. struct kvm_x86_ops *kvm_x86_ops;
  82. EXPORT_SYMBOL_GPL(kvm_x86_ops);
  83. static bool ignore_msrs = 0;
  84. module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
  85. bool kvm_has_tsc_control;
  86. EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
  87. u32 kvm_max_guest_tsc_khz;
  88. EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
  89. /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
  90. static u32 tsc_tolerance_ppm = 250;
  91. module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
  92. #define KVM_NR_SHARED_MSRS 16
  93. struct kvm_shared_msrs_global {
  94. int nr;
  95. u32 msrs[KVM_NR_SHARED_MSRS];
  96. };
  97. struct kvm_shared_msrs {
  98. struct user_return_notifier urn;
  99. bool registered;
  100. struct kvm_shared_msr_values {
  101. u64 host;
  102. u64 curr;
  103. } values[KVM_NR_SHARED_MSRS];
  104. };
  105. static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
  106. static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
  107. struct kvm_stats_debugfs_item debugfs_entries[] = {
  108. { "pf_fixed", VCPU_STAT(pf_fixed) },
  109. { "pf_guest", VCPU_STAT(pf_guest) },
  110. { "tlb_flush", VCPU_STAT(tlb_flush) },
  111. { "invlpg", VCPU_STAT(invlpg) },
  112. { "exits", VCPU_STAT(exits) },
  113. { "io_exits", VCPU_STAT(io_exits) },
  114. { "mmio_exits", VCPU_STAT(mmio_exits) },
  115. { "signal_exits", VCPU_STAT(signal_exits) },
  116. { "irq_window", VCPU_STAT(irq_window_exits) },
  117. { "nmi_window", VCPU_STAT(nmi_window_exits) },
  118. { "halt_exits", VCPU_STAT(halt_exits) },
  119. { "halt_wakeup", VCPU_STAT(halt_wakeup) },
  120. { "hypercalls", VCPU_STAT(hypercalls) },
  121. { "request_irq", VCPU_STAT(request_irq_exits) },
  122. { "irq_exits", VCPU_STAT(irq_exits) },
  123. { "host_state_reload", VCPU_STAT(host_state_reload) },
  124. { "efer_reload", VCPU_STAT(efer_reload) },
  125. { "fpu_reload", VCPU_STAT(fpu_reload) },
  126. { "insn_emulation", VCPU_STAT(insn_emulation) },
  127. { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
  128. { "irq_injections", VCPU_STAT(irq_injections) },
  129. { "nmi_injections", VCPU_STAT(nmi_injections) },
  130. { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
  131. { "mmu_pte_write", VM_STAT(mmu_pte_write) },
  132. { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
  133. { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
  134. { "mmu_flooded", VM_STAT(mmu_flooded) },
  135. { "mmu_recycled", VM_STAT(mmu_recycled) },
  136. { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
  137. { "mmu_unsync", VM_STAT(mmu_unsync) },
  138. { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
  139. { "largepages", VM_STAT(lpages) },
  140. { NULL }
  141. };
  142. u64 __read_mostly host_xcr0;
  143. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
  144. static int kvm_vcpu_reset(struct kvm_vcpu *vcpu);
  145. static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  146. {
  147. int i;
  148. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
  149. vcpu->arch.apf.gfns[i] = ~0;
  150. }
  151. static void kvm_on_user_return(struct user_return_notifier *urn)
  152. {
  153. unsigned slot;
  154. struct kvm_shared_msrs *locals
  155. = container_of(urn, struct kvm_shared_msrs, urn);
  156. struct kvm_shared_msr_values *values;
  157. for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
  158. values = &locals->values[slot];
  159. if (values->host != values->curr) {
  160. wrmsrl(shared_msrs_global.msrs[slot], values->host);
  161. values->curr = values->host;
  162. }
  163. }
  164. locals->registered = false;
  165. user_return_notifier_unregister(urn);
  166. }
  167. static void shared_msr_update(unsigned slot, u32 msr)
  168. {
  169. struct kvm_shared_msrs *smsr;
  170. u64 value;
  171. smsr = &__get_cpu_var(shared_msrs);
  172. /* only read, and nobody should modify it at this time,
  173. * so don't need lock */
  174. if (slot >= shared_msrs_global.nr) {
  175. printk(KERN_ERR "kvm: invalid MSR slot!");
  176. return;
  177. }
  178. rdmsrl_safe(msr, &value);
  179. smsr->values[slot].host = value;
  180. smsr->values[slot].curr = value;
  181. }
  182. void kvm_define_shared_msr(unsigned slot, u32 msr)
  183. {
  184. if (slot >= shared_msrs_global.nr)
  185. shared_msrs_global.nr = slot + 1;
  186. shared_msrs_global.msrs[slot] = msr;
  187. /* we need ensured the shared_msr_global have been updated */
  188. smp_wmb();
  189. }
  190. EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
  191. static void kvm_shared_msr_cpu_online(void)
  192. {
  193. unsigned i;
  194. for (i = 0; i < shared_msrs_global.nr; ++i)
  195. shared_msr_update(i, shared_msrs_global.msrs[i]);
  196. }
  197. void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
  198. {
  199. struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
  200. if (((value ^ smsr->values[slot].curr) & mask) == 0)
  201. return;
  202. smsr->values[slot].curr = value;
  203. wrmsrl(shared_msrs_global.msrs[slot], value);
  204. if (!smsr->registered) {
  205. smsr->urn.on_user_return = kvm_on_user_return;
  206. user_return_notifier_register(&smsr->urn);
  207. smsr->registered = true;
  208. }
  209. }
  210. EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
  211. static void drop_user_return_notifiers(void *ignore)
  212. {
  213. struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
  214. if (smsr->registered)
  215. kvm_on_user_return(&smsr->urn);
  216. }
  217. u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  218. {
  219. return vcpu->arch.apic_base;
  220. }
  221. EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  222. void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
  223. {
  224. /* TODO: reserve bits check */
  225. kvm_lapic_set_base(vcpu, data);
  226. }
  227. EXPORT_SYMBOL_GPL(kvm_set_apic_base);
  228. #define EXCPT_BENIGN 0
  229. #define EXCPT_CONTRIBUTORY 1
  230. #define EXCPT_PF 2
  231. static int exception_class(int vector)
  232. {
  233. switch (vector) {
  234. case PF_VECTOR:
  235. return EXCPT_PF;
  236. case DE_VECTOR:
  237. case TS_VECTOR:
  238. case NP_VECTOR:
  239. case SS_VECTOR:
  240. case GP_VECTOR:
  241. return EXCPT_CONTRIBUTORY;
  242. default:
  243. break;
  244. }
  245. return EXCPT_BENIGN;
  246. }
  247. static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
  248. unsigned nr, bool has_error, u32 error_code,
  249. bool reinject)
  250. {
  251. u32 prev_nr;
  252. int class1, class2;
  253. kvm_make_request(KVM_REQ_EVENT, vcpu);
  254. if (!vcpu->arch.exception.pending) {
  255. queue:
  256. vcpu->arch.exception.pending = true;
  257. vcpu->arch.exception.has_error_code = has_error;
  258. vcpu->arch.exception.nr = nr;
  259. vcpu->arch.exception.error_code = error_code;
  260. vcpu->arch.exception.reinject = reinject;
  261. return;
  262. }
  263. /* to check exception */
  264. prev_nr = vcpu->arch.exception.nr;
  265. if (prev_nr == DF_VECTOR) {
  266. /* triple fault -> shutdown */
  267. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  268. return;
  269. }
  270. class1 = exception_class(prev_nr);
  271. class2 = exception_class(nr);
  272. if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
  273. || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  274. /* generate double fault per SDM Table 5-5 */
  275. vcpu->arch.exception.pending = true;
  276. vcpu->arch.exception.has_error_code = true;
  277. vcpu->arch.exception.nr = DF_VECTOR;
  278. vcpu->arch.exception.error_code = 0;
  279. } else
  280. /* replace previous exception with a new one in a hope
  281. that instruction re-execution will regenerate lost
  282. exception */
  283. goto queue;
  284. }
  285. void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  286. {
  287. kvm_multiple_exception(vcpu, nr, false, 0, false);
  288. }
  289. EXPORT_SYMBOL_GPL(kvm_queue_exception);
  290. void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  291. {
  292. kvm_multiple_exception(vcpu, nr, false, 0, true);
  293. }
  294. EXPORT_SYMBOL_GPL(kvm_requeue_exception);
  295. void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
  296. {
  297. if (err)
  298. kvm_inject_gp(vcpu, 0);
  299. else
  300. kvm_x86_ops->skip_emulated_instruction(vcpu);
  301. }
  302. EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
  303. void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  304. {
  305. ++vcpu->stat.pf_guest;
  306. vcpu->arch.cr2 = fault->address;
  307. kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
  308. }
  309. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  310. void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  311. {
  312. if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  313. vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
  314. else
  315. vcpu->arch.mmu.inject_page_fault(vcpu, fault);
  316. }
  317. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  318. {
  319. atomic_inc(&vcpu->arch.nmi_queued);
  320. kvm_make_request(KVM_REQ_NMI, vcpu);
  321. }
  322. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  323. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  324. {
  325. kvm_multiple_exception(vcpu, nr, true, error_code, false);
  326. }
  327. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  328. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  329. {
  330. kvm_multiple_exception(vcpu, nr, true, error_code, true);
  331. }
  332. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  333. /*
  334. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  335. * a #GP and return false.
  336. */
  337. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  338. {
  339. if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  340. return true;
  341. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  342. return false;
  343. }
  344. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  345. /*
  346. * This function will be used to read from the physical memory of the currently
  347. * running guest. The difference to kvm_read_guest_page is that this function
  348. * can read from guest physical or from the guest's guest physical memory.
  349. */
  350. int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  351. gfn_t ngfn, void *data, int offset, int len,
  352. u32 access)
  353. {
  354. gfn_t real_gfn;
  355. gpa_t ngpa;
  356. ngpa = gfn_to_gpa(ngfn);
  357. real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
  358. if (real_gfn == UNMAPPED_GVA)
  359. return -EFAULT;
  360. real_gfn = gpa_to_gfn(real_gfn);
  361. return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
  362. }
  363. EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
  364. int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  365. void *data, int offset, int len, u32 access)
  366. {
  367. return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  368. data, offset, len, access);
  369. }
  370. /*
  371. * Load the pae pdptrs. Return true is they are all valid.
  372. */
  373. int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
  374. {
  375. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  376. unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  377. int i;
  378. int ret;
  379. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  380. ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  381. offset * sizeof(u64), sizeof(pdpte),
  382. PFERR_USER_MASK|PFERR_WRITE_MASK);
  383. if (ret < 0) {
  384. ret = 0;
  385. goto out;
  386. }
  387. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  388. if (is_present_gpte(pdpte[i]) &&
  389. (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
  390. ret = 0;
  391. goto out;
  392. }
  393. }
  394. ret = 1;
  395. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  396. __set_bit(VCPU_EXREG_PDPTR,
  397. (unsigned long *)&vcpu->arch.regs_avail);
  398. __set_bit(VCPU_EXREG_PDPTR,
  399. (unsigned long *)&vcpu->arch.regs_dirty);
  400. out:
  401. return ret;
  402. }
  403. EXPORT_SYMBOL_GPL(load_pdptrs);
  404. static bool pdptrs_changed(struct kvm_vcpu *vcpu)
  405. {
  406. u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
  407. bool changed = true;
  408. int offset;
  409. gfn_t gfn;
  410. int r;
  411. if (is_long_mode(vcpu) || !is_pae(vcpu))
  412. return false;
  413. if (!test_bit(VCPU_EXREG_PDPTR,
  414. (unsigned long *)&vcpu->arch.regs_avail))
  415. return true;
  416. gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
  417. offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
  418. r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  419. PFERR_USER_MASK | PFERR_WRITE_MASK);
  420. if (r < 0)
  421. goto out;
  422. changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
  423. out:
  424. return changed;
  425. }
  426. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  427. {
  428. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  429. unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
  430. X86_CR0_CD | X86_CR0_NW;
  431. cr0 |= X86_CR0_ET;
  432. #ifdef CONFIG_X86_64
  433. if (cr0 & 0xffffffff00000000UL)
  434. return 1;
  435. #endif
  436. cr0 &= ~CR0_RESERVED_BITS;
  437. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  438. return 1;
  439. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  440. return 1;
  441. if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  442. #ifdef CONFIG_X86_64
  443. if ((vcpu->arch.efer & EFER_LME)) {
  444. int cs_db, cs_l;
  445. if (!is_pae(vcpu))
  446. return 1;
  447. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  448. if (cs_l)
  449. return 1;
  450. } else
  451. #endif
  452. if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  453. kvm_read_cr3(vcpu)))
  454. return 1;
  455. }
  456. if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  457. return 1;
  458. kvm_x86_ops->set_cr0(vcpu, cr0);
  459. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  460. kvm_clear_async_pf_completion_queue(vcpu);
  461. kvm_async_pf_hash_reset(vcpu);
  462. }
  463. if ((cr0 ^ old_cr0) & update_bits)
  464. kvm_mmu_reset_context(vcpu);
  465. return 0;
  466. }
  467. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  468. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  469. {
  470. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  471. }
  472. EXPORT_SYMBOL_GPL(kvm_lmsw);
  473. int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  474. {
  475. u64 xcr0;
  476. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  477. if (index != XCR_XFEATURE_ENABLED_MASK)
  478. return 1;
  479. xcr0 = xcr;
  480. if (kvm_x86_ops->get_cpl(vcpu) != 0)
  481. return 1;
  482. if (!(xcr0 & XSTATE_FP))
  483. return 1;
  484. if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
  485. return 1;
  486. if (xcr0 & ~host_xcr0)
  487. return 1;
  488. vcpu->arch.xcr0 = xcr0;
  489. vcpu->guest_xcr0_loaded = 0;
  490. return 0;
  491. }
  492. int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  493. {
  494. if (__kvm_set_xcr(vcpu, index, xcr)) {
  495. kvm_inject_gp(vcpu, 0);
  496. return 1;
  497. }
  498. return 0;
  499. }
  500. EXPORT_SYMBOL_GPL(kvm_set_xcr);
  501. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  502. {
  503. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  504. unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
  505. X86_CR4_PAE | X86_CR4_SMEP;
  506. if (cr4 & CR4_RESERVED_BITS)
  507. return 1;
  508. if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
  509. return 1;
  510. if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
  511. return 1;
  512. if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
  513. return 1;
  514. if (is_long_mode(vcpu)) {
  515. if (!(cr4 & X86_CR4_PAE))
  516. return 1;
  517. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  518. && ((cr4 ^ old_cr4) & pdptr_bits)
  519. && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  520. kvm_read_cr3(vcpu)))
  521. return 1;
  522. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  523. if (!guest_cpuid_has_pcid(vcpu))
  524. return 1;
  525. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  526. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  527. return 1;
  528. }
  529. if (kvm_x86_ops->set_cr4(vcpu, cr4))
  530. return 1;
  531. if (((cr4 ^ old_cr4) & pdptr_bits) ||
  532. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  533. kvm_mmu_reset_context(vcpu);
  534. if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
  535. kvm_update_cpuid(vcpu);
  536. return 0;
  537. }
  538. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  539. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  540. {
  541. if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
  542. kvm_mmu_sync_roots(vcpu);
  543. kvm_mmu_flush_tlb(vcpu);
  544. return 0;
  545. }
  546. if (is_long_mode(vcpu)) {
  547. if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
  548. if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
  549. return 1;
  550. } else
  551. if (cr3 & CR3_L_MODE_RESERVED_BITS)
  552. return 1;
  553. } else {
  554. if (is_pae(vcpu)) {
  555. if (cr3 & CR3_PAE_RESERVED_BITS)
  556. return 1;
  557. if (is_paging(vcpu) &&
  558. !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
  559. return 1;
  560. }
  561. /*
  562. * We don't check reserved bits in nonpae mode, because
  563. * this isn't enforced, and VMware depends on this.
  564. */
  565. }
  566. /*
  567. * Does the new cr3 value map to physical memory? (Note, we
  568. * catch an invalid cr3 even in real-mode, because it would
  569. * cause trouble later on when we turn on paging anyway.)
  570. *
  571. * A real CPU would silently accept an invalid cr3 and would
  572. * attempt to use it - with largely undefined (and often hard
  573. * to debug) behavior on the guest side.
  574. */
  575. if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
  576. return 1;
  577. vcpu->arch.cr3 = cr3;
  578. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  579. vcpu->arch.mmu.new_cr3(vcpu);
  580. return 0;
  581. }
  582. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  583. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  584. {
  585. if (cr8 & CR8_RESERVED_BITS)
  586. return 1;
  587. if (irqchip_in_kernel(vcpu->kvm))
  588. kvm_lapic_set_tpr(vcpu, cr8);
  589. else
  590. vcpu->arch.cr8 = cr8;
  591. return 0;
  592. }
  593. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  594. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  595. {
  596. if (irqchip_in_kernel(vcpu->kvm))
  597. return kvm_lapic_get_cr8(vcpu);
  598. else
  599. return vcpu->arch.cr8;
  600. }
  601. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  602. static void kvm_update_dr7(struct kvm_vcpu *vcpu)
  603. {
  604. unsigned long dr7;
  605. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  606. dr7 = vcpu->arch.guest_debug_dr7;
  607. else
  608. dr7 = vcpu->arch.dr7;
  609. kvm_x86_ops->set_dr7(vcpu, dr7);
  610. vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
  611. }
  612. static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  613. {
  614. switch (dr) {
  615. case 0 ... 3:
  616. vcpu->arch.db[dr] = val;
  617. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  618. vcpu->arch.eff_db[dr] = val;
  619. break;
  620. case 4:
  621. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  622. return 1; /* #UD */
  623. /* fall through */
  624. case 6:
  625. if (val & 0xffffffff00000000ULL)
  626. return -1; /* #GP */
  627. vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
  628. break;
  629. case 5:
  630. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  631. return 1; /* #UD */
  632. /* fall through */
  633. default: /* 7 */
  634. if (val & 0xffffffff00000000ULL)
  635. return -1; /* #GP */
  636. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  637. kvm_update_dr7(vcpu);
  638. break;
  639. }
  640. return 0;
  641. }
  642. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  643. {
  644. int res;
  645. res = __kvm_set_dr(vcpu, dr, val);
  646. if (res > 0)
  647. kvm_queue_exception(vcpu, UD_VECTOR);
  648. else if (res < 0)
  649. kvm_inject_gp(vcpu, 0);
  650. return res;
  651. }
  652. EXPORT_SYMBOL_GPL(kvm_set_dr);
  653. static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  654. {
  655. switch (dr) {
  656. case 0 ... 3:
  657. *val = vcpu->arch.db[dr];
  658. break;
  659. case 4:
  660. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  661. return 1;
  662. /* fall through */
  663. case 6:
  664. *val = vcpu->arch.dr6;
  665. break;
  666. case 5:
  667. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  668. return 1;
  669. /* fall through */
  670. default: /* 7 */
  671. *val = vcpu->arch.dr7;
  672. break;
  673. }
  674. return 0;
  675. }
  676. int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  677. {
  678. if (_kvm_get_dr(vcpu, dr, val)) {
  679. kvm_queue_exception(vcpu, UD_VECTOR);
  680. return 1;
  681. }
  682. return 0;
  683. }
  684. EXPORT_SYMBOL_GPL(kvm_get_dr);
  685. bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  686. {
  687. u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  688. u64 data;
  689. int err;
  690. err = kvm_pmu_read_pmc(vcpu, ecx, &data);
  691. if (err)
  692. return err;
  693. kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  694. kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  695. return err;
  696. }
  697. EXPORT_SYMBOL_GPL(kvm_rdpmc);
  698. /*
  699. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  700. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  701. *
  702. * This list is modified at module load time to reflect the
  703. * capabilities of the host cpu. This capabilities test skips MSRs that are
  704. * kvm-specific. Those are put in the beginning of the list.
  705. */
  706. #define KVM_SAVE_MSRS_BEGIN 10
  707. static u32 msrs_to_save[] = {
  708. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  709. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  710. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  711. HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  712. MSR_KVM_PV_EOI_EN,
  713. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  714. MSR_STAR,
  715. #ifdef CONFIG_X86_64
  716. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  717. #endif
  718. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
  719. };
  720. static unsigned num_msrs_to_save;
  721. static const u32 emulated_msrs[] = {
  722. MSR_IA32_TSCDEADLINE,
  723. MSR_IA32_MISC_ENABLE,
  724. MSR_IA32_MCG_STATUS,
  725. MSR_IA32_MCG_CTL,
  726. };
  727. static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
  728. {
  729. u64 old_efer = vcpu->arch.efer;
  730. if (efer & efer_reserved_bits)
  731. return 1;
  732. if (is_paging(vcpu)
  733. && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  734. return 1;
  735. if (efer & EFER_FFXSR) {
  736. struct kvm_cpuid_entry2 *feat;
  737. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  738. if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
  739. return 1;
  740. }
  741. if (efer & EFER_SVME) {
  742. struct kvm_cpuid_entry2 *feat;
  743. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  744. if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
  745. return 1;
  746. }
  747. efer &= ~EFER_LMA;
  748. efer |= vcpu->arch.efer & EFER_LMA;
  749. kvm_x86_ops->set_efer(vcpu, efer);
  750. vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
  751. /* Update reserved bits */
  752. if ((efer ^ old_efer) & EFER_NX)
  753. kvm_mmu_reset_context(vcpu);
  754. return 0;
  755. }
  756. void kvm_enable_efer_bits(u64 mask)
  757. {
  758. efer_reserved_bits &= ~mask;
  759. }
  760. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  761. /*
  762. * Writes msr value into into the appropriate "register".
  763. * Returns 0 on success, non-0 otherwise.
  764. * Assumes vcpu_load() was already called.
  765. */
  766. int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
  767. {
  768. return kvm_x86_ops->set_msr(vcpu, msr_index, data);
  769. }
  770. /*
  771. * Adapt set_msr() to msr_io()'s calling convention
  772. */
  773. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  774. {
  775. return kvm_set_msr(vcpu, index, *data);
  776. }
  777. #ifdef CONFIG_X86_64
  778. struct pvclock_gtod_data {
  779. seqcount_t seq;
  780. struct { /* extract of a clocksource struct */
  781. int vclock_mode;
  782. cycle_t cycle_last;
  783. cycle_t mask;
  784. u32 mult;
  785. u32 shift;
  786. } clock;
  787. /* open coded 'struct timespec' */
  788. u64 monotonic_time_snsec;
  789. time_t monotonic_time_sec;
  790. };
  791. static struct pvclock_gtod_data pvclock_gtod_data;
  792. static void update_pvclock_gtod(struct timekeeper *tk)
  793. {
  794. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  795. write_seqcount_begin(&vdata->seq);
  796. /* copy pvclock gtod data */
  797. vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
  798. vdata->clock.cycle_last = tk->clock->cycle_last;
  799. vdata->clock.mask = tk->clock->mask;
  800. vdata->clock.mult = tk->mult;
  801. vdata->clock.shift = tk->shift;
  802. vdata->monotonic_time_sec = tk->xtime_sec
  803. + tk->wall_to_monotonic.tv_sec;
  804. vdata->monotonic_time_snsec = tk->xtime_nsec
  805. + (tk->wall_to_monotonic.tv_nsec
  806. << tk->shift);
  807. while (vdata->monotonic_time_snsec >=
  808. (((u64)NSEC_PER_SEC) << tk->shift)) {
  809. vdata->monotonic_time_snsec -=
  810. ((u64)NSEC_PER_SEC) << tk->shift;
  811. vdata->monotonic_time_sec++;
  812. }
  813. write_seqcount_end(&vdata->seq);
  814. }
  815. #endif
  816. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  817. {
  818. int version;
  819. int r;
  820. struct pvclock_wall_clock wc;
  821. struct timespec boot;
  822. if (!wall_clock)
  823. return;
  824. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  825. if (r)
  826. return;
  827. if (version & 1)
  828. ++version; /* first time write, random junk */
  829. ++version;
  830. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  831. /*
  832. * The guest calculates current wall clock time by adding
  833. * system time (updated by kvm_guest_time_update below) to the
  834. * wall clock specified here. guest system time equals host
  835. * system time for us, thus we must fill in host boot time here.
  836. */
  837. getboottime(&boot);
  838. if (kvm->arch.kvmclock_offset) {
  839. struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
  840. boot = timespec_sub(boot, ts);
  841. }
  842. wc.sec = boot.tv_sec;
  843. wc.nsec = boot.tv_nsec;
  844. wc.version = version;
  845. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  846. version++;
  847. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  848. }
  849. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  850. {
  851. uint32_t quotient, remainder;
  852. /* Don't try to replace with do_div(), this one calculates
  853. * "(dividend << 32) / divisor" */
  854. __asm__ ( "divl %4"
  855. : "=a" (quotient), "=d" (remainder)
  856. : "0" (0), "1" (dividend), "r" (divisor) );
  857. return quotient;
  858. }
  859. static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
  860. s8 *pshift, u32 *pmultiplier)
  861. {
  862. uint64_t scaled64;
  863. int32_t shift = 0;
  864. uint64_t tps64;
  865. uint32_t tps32;
  866. tps64 = base_khz * 1000LL;
  867. scaled64 = scaled_khz * 1000LL;
  868. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  869. tps64 >>= 1;
  870. shift--;
  871. }
  872. tps32 = (uint32_t)tps64;
  873. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  874. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  875. scaled64 >>= 1;
  876. else
  877. tps32 <<= 1;
  878. shift++;
  879. }
  880. *pshift = shift;
  881. *pmultiplier = div_frac(scaled64, tps32);
  882. pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
  883. __func__, base_khz, scaled_khz, shift, *pmultiplier);
  884. }
  885. static inline u64 get_kernel_ns(void)
  886. {
  887. struct timespec ts;
  888. WARN_ON(preemptible());
  889. ktime_get_ts(&ts);
  890. monotonic_to_bootbased(&ts);
  891. return timespec_to_ns(&ts);
  892. }
  893. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  894. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  895. unsigned long max_tsc_khz;
  896. static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
  897. {
  898. return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
  899. vcpu->arch.virtual_tsc_shift);
  900. }
  901. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  902. {
  903. u64 v = (u64)khz * (1000000 + ppm);
  904. do_div(v, 1000000);
  905. return v;
  906. }
  907. static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
  908. {
  909. u32 thresh_lo, thresh_hi;
  910. int use_scaling = 0;
  911. /* Compute a scale to convert nanoseconds in TSC cycles */
  912. kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
  913. &vcpu->arch.virtual_tsc_shift,
  914. &vcpu->arch.virtual_tsc_mult);
  915. vcpu->arch.virtual_tsc_khz = this_tsc_khz;
  916. /*
  917. * Compute the variation in TSC rate which is acceptable
  918. * within the range of tolerance and decide if the
  919. * rate being applied is within that bounds of the hardware
  920. * rate. If so, no scaling or compensation need be done.
  921. */
  922. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  923. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  924. if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
  925. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
  926. use_scaling = 1;
  927. }
  928. kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
  929. }
  930. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  931. {
  932. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  933. vcpu->arch.virtual_tsc_mult,
  934. vcpu->arch.virtual_tsc_shift);
  935. tsc += vcpu->arch.this_tsc_write;
  936. return tsc;
  937. }
  938. void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
  939. {
  940. struct kvm *kvm = vcpu->kvm;
  941. u64 offset, ns, elapsed;
  942. unsigned long flags;
  943. s64 usdiff;
  944. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  945. offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
  946. ns = get_kernel_ns();
  947. elapsed = ns - kvm->arch.last_tsc_nsec;
  948. /* n.b - signed multiplication and division required */
  949. usdiff = data - kvm->arch.last_tsc_write;
  950. #ifdef CONFIG_X86_64
  951. usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
  952. #else
  953. /* do_div() only does unsigned */
  954. asm("idivl %2; xor %%edx, %%edx"
  955. : "=A"(usdiff)
  956. : "A"(usdiff * 1000), "rm"(vcpu->arch.virtual_tsc_khz));
  957. #endif
  958. do_div(elapsed, 1000);
  959. usdiff -= elapsed;
  960. if (usdiff < 0)
  961. usdiff = -usdiff;
  962. /*
  963. * Special case: TSC write with a small delta (1 second) of virtual
  964. * cycle time against real time is interpreted as an attempt to
  965. * synchronize the CPU.
  966. *
  967. * For a reliable TSC, we can match TSC offsets, and for an unstable
  968. * TSC, we add elapsed time in this computation. We could let the
  969. * compensation code attempt to catch up if we fall behind, but
  970. * it's better to try to match offsets from the beginning.
  971. */
  972. if (usdiff < USEC_PER_SEC &&
  973. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  974. if (!check_tsc_unstable()) {
  975. offset = kvm->arch.cur_tsc_offset;
  976. pr_debug("kvm: matched tsc offset for %llu\n", data);
  977. } else {
  978. u64 delta = nsec_to_cycles(vcpu, elapsed);
  979. data += delta;
  980. offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
  981. pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
  982. }
  983. } else {
  984. /*
  985. * We split periods of matched TSC writes into generations.
  986. * For each generation, we track the original measured
  987. * nanosecond time, offset, and write, so if TSCs are in
  988. * sync, we can match exact offset, and if not, we can match
  989. * exact software computation in compute_guest_tsc()
  990. *
  991. * These values are tracked in kvm->arch.cur_xxx variables.
  992. */
  993. kvm->arch.cur_tsc_generation++;
  994. kvm->arch.cur_tsc_nsec = ns;
  995. kvm->arch.cur_tsc_write = data;
  996. kvm->arch.cur_tsc_offset = offset;
  997. pr_debug("kvm: new tsc generation %u, clock %llu\n",
  998. kvm->arch.cur_tsc_generation, data);
  999. }
  1000. /*
  1001. * We also track th most recent recorded KHZ, write and time to
  1002. * allow the matching interval to be extended at each write.
  1003. */
  1004. kvm->arch.last_tsc_nsec = ns;
  1005. kvm->arch.last_tsc_write = data;
  1006. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  1007. /* Reset of TSC must disable overshoot protection below */
  1008. vcpu->arch.hv_clock.tsc_timestamp = 0;
  1009. vcpu->arch.last_guest_tsc = data;
  1010. /* Keep track of which generation this VCPU has synchronized to */
  1011. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  1012. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  1013. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  1014. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  1015. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  1016. }
  1017. EXPORT_SYMBOL_GPL(kvm_write_tsc);
  1018. static int kvm_guest_time_update(struct kvm_vcpu *v)
  1019. {
  1020. unsigned long flags;
  1021. struct kvm_vcpu_arch *vcpu = &v->arch;
  1022. void *shared_kaddr;
  1023. unsigned long this_tsc_khz;
  1024. s64 kernel_ns, max_kernel_ns;
  1025. u64 tsc_timestamp;
  1026. struct pvclock_vcpu_time_info *guest_hv_clock;
  1027. u8 pvclock_flags;
  1028. /* Keep irq disabled to prevent changes to the clock */
  1029. local_irq_save(flags);
  1030. tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, native_read_tsc());
  1031. kernel_ns = get_kernel_ns();
  1032. this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
  1033. if (unlikely(this_tsc_khz == 0)) {
  1034. local_irq_restore(flags);
  1035. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1036. return 1;
  1037. }
  1038. /*
  1039. * We may have to catch up the TSC to match elapsed wall clock
  1040. * time for two reasons, even if kvmclock is used.
  1041. * 1) CPU could have been running below the maximum TSC rate
  1042. * 2) Broken TSC compensation resets the base at each VCPU
  1043. * entry to avoid unknown leaps of TSC even when running
  1044. * again on the same CPU. This may cause apparent elapsed
  1045. * time to disappear, and the guest to stand still or run
  1046. * very slowly.
  1047. */
  1048. if (vcpu->tsc_catchup) {
  1049. u64 tsc = compute_guest_tsc(v, kernel_ns);
  1050. if (tsc > tsc_timestamp) {
  1051. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  1052. tsc_timestamp = tsc;
  1053. }
  1054. }
  1055. local_irq_restore(flags);
  1056. if (!vcpu->time_page)
  1057. return 0;
  1058. /*
  1059. * Time as measured by the TSC may go backwards when resetting the base
  1060. * tsc_timestamp. The reason for this is that the TSC resolution is
  1061. * higher than the resolution of the other clock scales. Thus, many
  1062. * possible measurments of the TSC correspond to one measurement of any
  1063. * other clock, and so a spread of values is possible. This is not a
  1064. * problem for the computation of the nanosecond clock; with TSC rates
  1065. * around 1GHZ, there can only be a few cycles which correspond to one
  1066. * nanosecond value, and any path through this code will inevitably
  1067. * take longer than that. However, with the kernel_ns value itself,
  1068. * the precision may be much lower, down to HZ granularity. If the
  1069. * first sampling of TSC against kernel_ns ends in the low part of the
  1070. * range, and the second in the high end of the range, we can get:
  1071. *
  1072. * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
  1073. *
  1074. * As the sampling errors potentially range in the thousands of cycles,
  1075. * it is possible such a time value has already been observed by the
  1076. * guest. To protect against this, we must compute the system time as
  1077. * observed by the guest and ensure the new system time is greater.
  1078. */
  1079. max_kernel_ns = 0;
  1080. if (vcpu->hv_clock.tsc_timestamp) {
  1081. max_kernel_ns = vcpu->last_guest_tsc -
  1082. vcpu->hv_clock.tsc_timestamp;
  1083. max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
  1084. vcpu->hv_clock.tsc_to_system_mul,
  1085. vcpu->hv_clock.tsc_shift);
  1086. max_kernel_ns += vcpu->last_kernel_ns;
  1087. }
  1088. if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
  1089. kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
  1090. &vcpu->hv_clock.tsc_shift,
  1091. &vcpu->hv_clock.tsc_to_system_mul);
  1092. vcpu->hw_tsc_khz = this_tsc_khz;
  1093. }
  1094. if (max_kernel_ns > kernel_ns)
  1095. kernel_ns = max_kernel_ns;
  1096. /* With all the info we got, fill in the values */
  1097. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  1098. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  1099. vcpu->last_kernel_ns = kernel_ns;
  1100. vcpu->last_guest_tsc = tsc_timestamp;
  1101. /*
  1102. * The interface expects us to write an even number signaling that the
  1103. * update is finished. Since the guest won't see the intermediate
  1104. * state, we just increase by 2 at the end.
  1105. */
  1106. vcpu->hv_clock.version += 2;
  1107. shared_kaddr = kmap_atomic(vcpu->time_page);
  1108. guest_hv_clock = shared_kaddr + vcpu->time_offset;
  1109. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  1110. pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
  1111. if (vcpu->pvclock_set_guest_stopped_request) {
  1112. pvclock_flags |= PVCLOCK_GUEST_STOPPED;
  1113. vcpu->pvclock_set_guest_stopped_request = false;
  1114. }
  1115. vcpu->hv_clock.flags = pvclock_flags;
  1116. memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
  1117. sizeof(vcpu->hv_clock));
  1118. kunmap_atomic(shared_kaddr);
  1119. mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
  1120. return 0;
  1121. }
  1122. static bool msr_mtrr_valid(unsigned msr)
  1123. {
  1124. switch (msr) {
  1125. case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
  1126. case MSR_MTRRfix64K_00000:
  1127. case MSR_MTRRfix16K_80000:
  1128. case MSR_MTRRfix16K_A0000:
  1129. case MSR_MTRRfix4K_C0000:
  1130. case MSR_MTRRfix4K_C8000:
  1131. case MSR_MTRRfix4K_D0000:
  1132. case MSR_MTRRfix4K_D8000:
  1133. case MSR_MTRRfix4K_E0000:
  1134. case MSR_MTRRfix4K_E8000:
  1135. case MSR_MTRRfix4K_F0000:
  1136. case MSR_MTRRfix4K_F8000:
  1137. case MSR_MTRRdefType:
  1138. case MSR_IA32_CR_PAT:
  1139. return true;
  1140. case 0x2f8:
  1141. return true;
  1142. }
  1143. return false;
  1144. }
  1145. static bool valid_pat_type(unsigned t)
  1146. {
  1147. return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
  1148. }
  1149. static bool valid_mtrr_type(unsigned t)
  1150. {
  1151. return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
  1152. }
  1153. static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1154. {
  1155. int i;
  1156. if (!msr_mtrr_valid(msr))
  1157. return false;
  1158. if (msr == MSR_IA32_CR_PAT) {
  1159. for (i = 0; i < 8; i++)
  1160. if (!valid_pat_type((data >> (i * 8)) & 0xff))
  1161. return false;
  1162. return true;
  1163. } else if (msr == MSR_MTRRdefType) {
  1164. if (data & ~0xcff)
  1165. return false;
  1166. return valid_mtrr_type(data & 0xff);
  1167. } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
  1168. for (i = 0; i < 8 ; i++)
  1169. if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
  1170. return false;
  1171. return true;
  1172. }
  1173. /* variable MTRRs */
  1174. return valid_mtrr_type(data & 0xff);
  1175. }
  1176. static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1177. {
  1178. u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
  1179. if (!mtrr_valid(vcpu, msr, data))
  1180. return 1;
  1181. if (msr == MSR_MTRRdefType) {
  1182. vcpu->arch.mtrr_state.def_type = data;
  1183. vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
  1184. } else if (msr == MSR_MTRRfix64K_00000)
  1185. p[0] = data;
  1186. else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  1187. p[1 + msr - MSR_MTRRfix16K_80000] = data;
  1188. else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  1189. p[3 + msr - MSR_MTRRfix4K_C0000] = data;
  1190. else if (msr == MSR_IA32_CR_PAT)
  1191. vcpu->arch.pat = data;
  1192. else { /* Variable MTRRs */
  1193. int idx, is_mtrr_mask;
  1194. u64 *pt;
  1195. idx = (msr - 0x200) / 2;
  1196. is_mtrr_mask = msr - 0x200 - 2 * idx;
  1197. if (!is_mtrr_mask)
  1198. pt =
  1199. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  1200. else
  1201. pt =
  1202. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  1203. *pt = data;
  1204. }
  1205. kvm_mmu_reset_context(vcpu);
  1206. return 0;
  1207. }
  1208. static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1209. {
  1210. u64 mcg_cap = vcpu->arch.mcg_cap;
  1211. unsigned bank_num = mcg_cap & 0xff;
  1212. switch (msr) {
  1213. case MSR_IA32_MCG_STATUS:
  1214. vcpu->arch.mcg_status = data;
  1215. break;
  1216. case MSR_IA32_MCG_CTL:
  1217. if (!(mcg_cap & MCG_CTL_P))
  1218. return 1;
  1219. if (data != 0 && data != ~(u64)0)
  1220. return -1;
  1221. vcpu->arch.mcg_ctl = data;
  1222. break;
  1223. default:
  1224. if (msr >= MSR_IA32_MC0_CTL &&
  1225. msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  1226. u32 offset = msr - MSR_IA32_MC0_CTL;
  1227. /* only 0 or all 1s can be written to IA32_MCi_CTL
  1228. * some Linux kernels though clear bit 10 in bank 4 to
  1229. * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  1230. * this to avoid an uncatched #GP in the guest
  1231. */
  1232. if ((offset & 0x3) == 0 &&
  1233. data != 0 && (data | (1 << 10)) != ~(u64)0)
  1234. return -1;
  1235. vcpu->arch.mce_banks[offset] = data;
  1236. break;
  1237. }
  1238. return 1;
  1239. }
  1240. return 0;
  1241. }
  1242. static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  1243. {
  1244. struct kvm *kvm = vcpu->kvm;
  1245. int lm = is_long_mode(vcpu);
  1246. u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  1247. : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  1248. u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  1249. : kvm->arch.xen_hvm_config.blob_size_32;
  1250. u32 page_num = data & ~PAGE_MASK;
  1251. u64 page_addr = data & PAGE_MASK;
  1252. u8 *page;
  1253. int r;
  1254. r = -E2BIG;
  1255. if (page_num >= blob_size)
  1256. goto out;
  1257. r = -ENOMEM;
  1258. page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  1259. if (IS_ERR(page)) {
  1260. r = PTR_ERR(page);
  1261. goto out;
  1262. }
  1263. if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
  1264. goto out_free;
  1265. r = 0;
  1266. out_free:
  1267. kfree(page);
  1268. out:
  1269. return r;
  1270. }
  1271. static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
  1272. {
  1273. return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
  1274. }
  1275. static bool kvm_hv_msr_partition_wide(u32 msr)
  1276. {
  1277. bool r = false;
  1278. switch (msr) {
  1279. case HV_X64_MSR_GUEST_OS_ID:
  1280. case HV_X64_MSR_HYPERCALL:
  1281. r = true;
  1282. break;
  1283. }
  1284. return r;
  1285. }
  1286. static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1287. {
  1288. struct kvm *kvm = vcpu->kvm;
  1289. switch (msr) {
  1290. case HV_X64_MSR_GUEST_OS_ID:
  1291. kvm->arch.hv_guest_os_id = data;
  1292. /* setting guest os id to zero disables hypercall page */
  1293. if (!kvm->arch.hv_guest_os_id)
  1294. kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
  1295. break;
  1296. case HV_X64_MSR_HYPERCALL: {
  1297. u64 gfn;
  1298. unsigned long addr;
  1299. u8 instructions[4];
  1300. /* if guest os id is not set hypercall should remain disabled */
  1301. if (!kvm->arch.hv_guest_os_id)
  1302. break;
  1303. if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
  1304. kvm->arch.hv_hypercall = data;
  1305. break;
  1306. }
  1307. gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
  1308. addr = gfn_to_hva(kvm, gfn);
  1309. if (kvm_is_error_hva(addr))
  1310. return 1;
  1311. kvm_x86_ops->patch_hypercall(vcpu, instructions);
  1312. ((unsigned char *)instructions)[3] = 0xc3; /* ret */
  1313. if (__copy_to_user((void __user *)addr, instructions, 4))
  1314. return 1;
  1315. kvm->arch.hv_hypercall = data;
  1316. break;
  1317. }
  1318. default:
  1319. vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  1320. "data 0x%llx\n", msr, data);
  1321. return 1;
  1322. }
  1323. return 0;
  1324. }
  1325. static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1326. {
  1327. switch (msr) {
  1328. case HV_X64_MSR_APIC_ASSIST_PAGE: {
  1329. unsigned long addr;
  1330. if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
  1331. vcpu->arch.hv_vapic = data;
  1332. break;
  1333. }
  1334. addr = gfn_to_hva(vcpu->kvm, data >>
  1335. HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
  1336. if (kvm_is_error_hva(addr))
  1337. return 1;
  1338. if (__clear_user((void __user *)addr, PAGE_SIZE))
  1339. return 1;
  1340. vcpu->arch.hv_vapic = data;
  1341. break;
  1342. }
  1343. case HV_X64_MSR_EOI:
  1344. return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
  1345. case HV_X64_MSR_ICR:
  1346. return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
  1347. case HV_X64_MSR_TPR:
  1348. return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
  1349. default:
  1350. vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  1351. "data 0x%llx\n", msr, data);
  1352. return 1;
  1353. }
  1354. return 0;
  1355. }
  1356. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  1357. {
  1358. gpa_t gpa = data & ~0x3f;
  1359. /* Bits 2:5 are reserved, Should be zero */
  1360. if (data & 0x3c)
  1361. return 1;
  1362. vcpu->arch.apf.msr_val = data;
  1363. if (!(data & KVM_ASYNC_PF_ENABLED)) {
  1364. kvm_clear_async_pf_completion_queue(vcpu);
  1365. kvm_async_pf_hash_reset(vcpu);
  1366. return 0;
  1367. }
  1368. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
  1369. return 1;
  1370. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  1371. kvm_async_pf_wakeup_all(vcpu);
  1372. return 0;
  1373. }
  1374. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  1375. {
  1376. if (vcpu->arch.time_page) {
  1377. kvm_release_page_dirty(vcpu->arch.time_page);
  1378. vcpu->arch.time_page = NULL;
  1379. }
  1380. }
  1381. static void accumulate_steal_time(struct kvm_vcpu *vcpu)
  1382. {
  1383. u64 delta;
  1384. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1385. return;
  1386. delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
  1387. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1388. vcpu->arch.st.accum_steal = delta;
  1389. }
  1390. static void record_steal_time(struct kvm_vcpu *vcpu)
  1391. {
  1392. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1393. return;
  1394. if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1395. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  1396. return;
  1397. vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
  1398. vcpu->arch.st.steal.version += 2;
  1399. vcpu->arch.st.accum_steal = 0;
  1400. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1401. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1402. }
  1403. int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1404. {
  1405. bool pr = false;
  1406. switch (msr) {
  1407. case MSR_EFER:
  1408. return set_efer(vcpu, data);
  1409. case MSR_K7_HWCR:
  1410. data &= ~(u64)0x40; /* ignore flush filter disable */
  1411. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  1412. data &= ~(u64)0x8; /* ignore TLB cache disable */
  1413. if (data != 0) {
  1414. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  1415. data);
  1416. return 1;
  1417. }
  1418. break;
  1419. case MSR_FAM10H_MMIO_CONF_BASE:
  1420. if (data != 0) {
  1421. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  1422. "0x%llx\n", data);
  1423. return 1;
  1424. }
  1425. break;
  1426. case MSR_AMD64_NB_CFG:
  1427. break;
  1428. case MSR_IA32_DEBUGCTLMSR:
  1429. if (!data) {
  1430. /* We support the non-activated case already */
  1431. break;
  1432. } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  1433. /* Values other than LBR and BTF are vendor-specific,
  1434. thus reserved and should throw a #GP */
  1435. return 1;
  1436. }
  1437. vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
  1438. __func__, data);
  1439. break;
  1440. case MSR_IA32_UCODE_REV:
  1441. case MSR_IA32_UCODE_WRITE:
  1442. case MSR_VM_HSAVE_PA:
  1443. case MSR_AMD64_PATCH_LOADER:
  1444. break;
  1445. case 0x200 ... 0x2ff:
  1446. return set_msr_mtrr(vcpu, msr, data);
  1447. case MSR_IA32_APICBASE:
  1448. kvm_set_apic_base(vcpu, data);
  1449. break;
  1450. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  1451. return kvm_x2apic_msr_write(vcpu, msr, data);
  1452. case MSR_IA32_TSCDEADLINE:
  1453. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  1454. break;
  1455. case MSR_IA32_MISC_ENABLE:
  1456. vcpu->arch.ia32_misc_enable_msr = data;
  1457. break;
  1458. case MSR_KVM_WALL_CLOCK_NEW:
  1459. case MSR_KVM_WALL_CLOCK:
  1460. vcpu->kvm->arch.wall_clock = data;
  1461. kvm_write_wall_clock(vcpu->kvm, data);
  1462. break;
  1463. case MSR_KVM_SYSTEM_TIME_NEW:
  1464. case MSR_KVM_SYSTEM_TIME: {
  1465. kvmclock_reset(vcpu);
  1466. vcpu->arch.time = data;
  1467. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1468. /* we verify if the enable bit is set... */
  1469. if (!(data & 1))
  1470. break;
  1471. /* ...but clean it before doing the actual write */
  1472. vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
  1473. vcpu->arch.time_page =
  1474. gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
  1475. if (is_error_page(vcpu->arch.time_page))
  1476. vcpu->arch.time_page = NULL;
  1477. break;
  1478. }
  1479. case MSR_KVM_ASYNC_PF_EN:
  1480. if (kvm_pv_enable_async_pf(vcpu, data))
  1481. return 1;
  1482. break;
  1483. case MSR_KVM_STEAL_TIME:
  1484. if (unlikely(!sched_info_on()))
  1485. return 1;
  1486. if (data & KVM_STEAL_RESERVED_MASK)
  1487. return 1;
  1488. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  1489. data & KVM_STEAL_VALID_BITS))
  1490. return 1;
  1491. vcpu->arch.st.msr_val = data;
  1492. if (!(data & KVM_MSR_ENABLED))
  1493. break;
  1494. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1495. preempt_disable();
  1496. accumulate_steal_time(vcpu);
  1497. preempt_enable();
  1498. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  1499. break;
  1500. case MSR_KVM_PV_EOI_EN:
  1501. if (kvm_lapic_enable_pv_eoi(vcpu, data))
  1502. return 1;
  1503. break;
  1504. case MSR_IA32_MCG_CTL:
  1505. case MSR_IA32_MCG_STATUS:
  1506. case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  1507. return set_msr_mce(vcpu, msr, data);
  1508. /* Performance counters are not protected by a CPUID bit,
  1509. * so we should check all of them in the generic path for the sake of
  1510. * cross vendor migration.
  1511. * Writing a zero into the event select MSRs disables them,
  1512. * which we perfectly emulate ;-). Any other value should be at least
  1513. * reported, some guests depend on them.
  1514. */
  1515. case MSR_K7_EVNTSEL0:
  1516. case MSR_K7_EVNTSEL1:
  1517. case MSR_K7_EVNTSEL2:
  1518. case MSR_K7_EVNTSEL3:
  1519. if (data != 0)
  1520. vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  1521. "0x%x data 0x%llx\n", msr, data);
  1522. break;
  1523. /* at least RHEL 4 unconditionally writes to the perfctr registers,
  1524. * so we ignore writes to make it happy.
  1525. */
  1526. case MSR_K7_PERFCTR0:
  1527. case MSR_K7_PERFCTR1:
  1528. case MSR_K7_PERFCTR2:
  1529. case MSR_K7_PERFCTR3:
  1530. vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  1531. "0x%x data 0x%llx\n", msr, data);
  1532. break;
  1533. case MSR_P6_PERFCTR0:
  1534. case MSR_P6_PERFCTR1:
  1535. pr = true;
  1536. case MSR_P6_EVNTSEL0:
  1537. case MSR_P6_EVNTSEL1:
  1538. if (kvm_pmu_msr(vcpu, msr))
  1539. return kvm_pmu_set_msr(vcpu, msr, data);
  1540. if (pr || data != 0)
  1541. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  1542. "0x%x data 0x%llx\n", msr, data);
  1543. break;
  1544. case MSR_K7_CLK_CTL:
  1545. /*
  1546. * Ignore all writes to this no longer documented MSR.
  1547. * Writes are only relevant for old K7 processors,
  1548. * all pre-dating SVM, but a recommended workaround from
  1549. * AMD for these chips. It is possible to specify the
  1550. * affected processor models on the command line, hence
  1551. * the need to ignore the workaround.
  1552. */
  1553. break;
  1554. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  1555. if (kvm_hv_msr_partition_wide(msr)) {
  1556. int r;
  1557. mutex_lock(&vcpu->kvm->lock);
  1558. r = set_msr_hyperv_pw(vcpu, msr, data);
  1559. mutex_unlock(&vcpu->kvm->lock);
  1560. return r;
  1561. } else
  1562. return set_msr_hyperv(vcpu, msr, data);
  1563. break;
  1564. case MSR_IA32_BBL_CR_CTL3:
  1565. /* Drop writes to this legacy MSR -- see rdmsr
  1566. * counterpart for further detail.
  1567. */
  1568. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
  1569. break;
  1570. case MSR_AMD64_OSVW_ID_LENGTH:
  1571. if (!guest_cpuid_has_osvw(vcpu))
  1572. return 1;
  1573. vcpu->arch.osvw.length = data;
  1574. break;
  1575. case MSR_AMD64_OSVW_STATUS:
  1576. if (!guest_cpuid_has_osvw(vcpu))
  1577. return 1;
  1578. vcpu->arch.osvw.status = data;
  1579. break;
  1580. default:
  1581. if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  1582. return xen_hvm_config(vcpu, data);
  1583. if (kvm_pmu_msr(vcpu, msr))
  1584. return kvm_pmu_set_msr(vcpu, msr, data);
  1585. if (!ignore_msrs) {
  1586. vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
  1587. msr, data);
  1588. return 1;
  1589. } else {
  1590. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
  1591. msr, data);
  1592. break;
  1593. }
  1594. }
  1595. return 0;
  1596. }
  1597. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  1598. /*
  1599. * Reads an msr value (of 'msr_index') into 'pdata'.
  1600. * Returns 0 on success, non-0 otherwise.
  1601. * Assumes vcpu_load() was already called.
  1602. */
  1603. int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
  1604. {
  1605. return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
  1606. }
  1607. static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1608. {
  1609. u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
  1610. if (!msr_mtrr_valid(msr))
  1611. return 1;
  1612. if (msr == MSR_MTRRdefType)
  1613. *pdata = vcpu->arch.mtrr_state.def_type +
  1614. (vcpu->arch.mtrr_state.enabled << 10);
  1615. else if (msr == MSR_MTRRfix64K_00000)
  1616. *pdata = p[0];
  1617. else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  1618. *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
  1619. else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  1620. *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
  1621. else if (msr == MSR_IA32_CR_PAT)
  1622. *pdata = vcpu->arch.pat;
  1623. else { /* Variable MTRRs */
  1624. int idx, is_mtrr_mask;
  1625. u64 *pt;
  1626. idx = (msr - 0x200) / 2;
  1627. is_mtrr_mask = msr - 0x200 - 2 * idx;
  1628. if (!is_mtrr_mask)
  1629. pt =
  1630. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  1631. else
  1632. pt =
  1633. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  1634. *pdata = *pt;
  1635. }
  1636. return 0;
  1637. }
  1638. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1639. {
  1640. u64 data;
  1641. u64 mcg_cap = vcpu->arch.mcg_cap;
  1642. unsigned bank_num = mcg_cap & 0xff;
  1643. switch (msr) {
  1644. case MSR_IA32_P5_MC_ADDR:
  1645. case MSR_IA32_P5_MC_TYPE:
  1646. data = 0;
  1647. break;
  1648. case MSR_IA32_MCG_CAP:
  1649. data = vcpu->arch.mcg_cap;
  1650. break;
  1651. case MSR_IA32_MCG_CTL:
  1652. if (!(mcg_cap & MCG_CTL_P))
  1653. return 1;
  1654. data = vcpu->arch.mcg_ctl;
  1655. break;
  1656. case MSR_IA32_MCG_STATUS:
  1657. data = vcpu->arch.mcg_status;
  1658. break;
  1659. default:
  1660. if (msr >= MSR_IA32_MC0_CTL &&
  1661. msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  1662. u32 offset = msr - MSR_IA32_MC0_CTL;
  1663. data = vcpu->arch.mce_banks[offset];
  1664. break;
  1665. }
  1666. return 1;
  1667. }
  1668. *pdata = data;
  1669. return 0;
  1670. }
  1671. static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1672. {
  1673. u64 data = 0;
  1674. struct kvm *kvm = vcpu->kvm;
  1675. switch (msr) {
  1676. case HV_X64_MSR_GUEST_OS_ID:
  1677. data = kvm->arch.hv_guest_os_id;
  1678. break;
  1679. case HV_X64_MSR_HYPERCALL:
  1680. data = kvm->arch.hv_hypercall;
  1681. break;
  1682. default:
  1683. vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
  1684. return 1;
  1685. }
  1686. *pdata = data;
  1687. return 0;
  1688. }
  1689. static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1690. {
  1691. u64 data = 0;
  1692. switch (msr) {
  1693. case HV_X64_MSR_VP_INDEX: {
  1694. int r;
  1695. struct kvm_vcpu *v;
  1696. kvm_for_each_vcpu(r, v, vcpu->kvm)
  1697. if (v == vcpu)
  1698. data = r;
  1699. break;
  1700. }
  1701. case HV_X64_MSR_EOI:
  1702. return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
  1703. case HV_X64_MSR_ICR:
  1704. return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
  1705. case HV_X64_MSR_TPR:
  1706. return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
  1707. case HV_X64_MSR_APIC_ASSIST_PAGE:
  1708. data = vcpu->arch.hv_vapic;
  1709. break;
  1710. default:
  1711. vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
  1712. return 1;
  1713. }
  1714. *pdata = data;
  1715. return 0;
  1716. }
  1717. int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1718. {
  1719. u64 data;
  1720. switch (msr) {
  1721. case MSR_IA32_PLATFORM_ID:
  1722. case MSR_IA32_EBL_CR_POWERON:
  1723. case MSR_IA32_DEBUGCTLMSR:
  1724. case MSR_IA32_LASTBRANCHFROMIP:
  1725. case MSR_IA32_LASTBRANCHTOIP:
  1726. case MSR_IA32_LASTINTFROMIP:
  1727. case MSR_IA32_LASTINTTOIP:
  1728. case MSR_K8_SYSCFG:
  1729. case MSR_K7_HWCR:
  1730. case MSR_VM_HSAVE_PA:
  1731. case MSR_K7_EVNTSEL0:
  1732. case MSR_K7_PERFCTR0:
  1733. case MSR_K8_INT_PENDING_MSG:
  1734. case MSR_AMD64_NB_CFG:
  1735. case MSR_FAM10H_MMIO_CONF_BASE:
  1736. data = 0;
  1737. break;
  1738. case MSR_P6_PERFCTR0:
  1739. case MSR_P6_PERFCTR1:
  1740. case MSR_P6_EVNTSEL0:
  1741. case MSR_P6_EVNTSEL1:
  1742. if (kvm_pmu_msr(vcpu, msr))
  1743. return kvm_pmu_get_msr(vcpu, msr, pdata);
  1744. data = 0;
  1745. break;
  1746. case MSR_IA32_UCODE_REV:
  1747. data = 0x100000000ULL;
  1748. break;
  1749. case MSR_MTRRcap:
  1750. data = 0x500 | KVM_NR_VAR_MTRR;
  1751. break;
  1752. case 0x200 ... 0x2ff:
  1753. return get_msr_mtrr(vcpu, msr, pdata);
  1754. case 0xcd: /* fsb frequency */
  1755. data = 3;
  1756. break;
  1757. /*
  1758. * MSR_EBC_FREQUENCY_ID
  1759. * Conservative value valid for even the basic CPU models.
  1760. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  1761. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  1762. * and 266MHz for model 3, or 4. Set Core Clock
  1763. * Frequency to System Bus Frequency Ratio to 1 (bits
  1764. * 31:24) even though these are only valid for CPU
  1765. * models > 2, however guests may end up dividing or
  1766. * multiplying by zero otherwise.
  1767. */
  1768. case MSR_EBC_FREQUENCY_ID:
  1769. data = 1 << 24;
  1770. break;
  1771. case MSR_IA32_APICBASE:
  1772. data = kvm_get_apic_base(vcpu);
  1773. break;
  1774. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  1775. return kvm_x2apic_msr_read(vcpu, msr, pdata);
  1776. break;
  1777. case MSR_IA32_TSCDEADLINE:
  1778. data = kvm_get_lapic_tscdeadline_msr(vcpu);
  1779. break;
  1780. case MSR_IA32_MISC_ENABLE:
  1781. data = vcpu->arch.ia32_misc_enable_msr;
  1782. break;
  1783. case MSR_IA32_PERF_STATUS:
  1784. /* TSC increment by tick */
  1785. data = 1000ULL;
  1786. /* CPU multiplier */
  1787. data |= (((uint64_t)4ULL) << 40);
  1788. break;
  1789. case MSR_EFER:
  1790. data = vcpu->arch.efer;
  1791. break;
  1792. case MSR_KVM_WALL_CLOCK:
  1793. case MSR_KVM_WALL_CLOCK_NEW:
  1794. data = vcpu->kvm->arch.wall_clock;
  1795. break;
  1796. case MSR_KVM_SYSTEM_TIME:
  1797. case MSR_KVM_SYSTEM_TIME_NEW:
  1798. data = vcpu->arch.time;
  1799. break;
  1800. case MSR_KVM_ASYNC_PF_EN:
  1801. data = vcpu->arch.apf.msr_val;
  1802. break;
  1803. case MSR_KVM_STEAL_TIME:
  1804. data = vcpu->arch.st.msr_val;
  1805. break;
  1806. case MSR_KVM_PV_EOI_EN:
  1807. data = vcpu->arch.pv_eoi.msr_val;
  1808. break;
  1809. case MSR_IA32_P5_MC_ADDR:
  1810. case MSR_IA32_P5_MC_TYPE:
  1811. case MSR_IA32_MCG_CAP:
  1812. case MSR_IA32_MCG_CTL:
  1813. case MSR_IA32_MCG_STATUS:
  1814. case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  1815. return get_msr_mce(vcpu, msr, pdata);
  1816. case MSR_K7_CLK_CTL:
  1817. /*
  1818. * Provide expected ramp-up count for K7. All other
  1819. * are set to zero, indicating minimum divisors for
  1820. * every field.
  1821. *
  1822. * This prevents guest kernels on AMD host with CPU
  1823. * type 6, model 8 and higher from exploding due to
  1824. * the rdmsr failing.
  1825. */
  1826. data = 0x20000000;
  1827. break;
  1828. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  1829. if (kvm_hv_msr_partition_wide(msr)) {
  1830. int r;
  1831. mutex_lock(&vcpu->kvm->lock);
  1832. r = get_msr_hyperv_pw(vcpu, msr, pdata);
  1833. mutex_unlock(&vcpu->kvm->lock);
  1834. return r;
  1835. } else
  1836. return get_msr_hyperv(vcpu, msr, pdata);
  1837. break;
  1838. case MSR_IA32_BBL_CR_CTL3:
  1839. /* This legacy MSR exists but isn't fully documented in current
  1840. * silicon. It is however accessed by winxp in very narrow
  1841. * scenarios where it sets bit #19, itself documented as
  1842. * a "reserved" bit. Best effort attempt to source coherent
  1843. * read data here should the balance of the register be
  1844. * interpreted by the guest:
  1845. *
  1846. * L2 cache control register 3: 64GB range, 256KB size,
  1847. * enabled, latency 0x1, configured
  1848. */
  1849. data = 0xbe702111;
  1850. break;
  1851. case MSR_AMD64_OSVW_ID_LENGTH:
  1852. if (!guest_cpuid_has_osvw(vcpu))
  1853. return 1;
  1854. data = vcpu->arch.osvw.length;
  1855. break;
  1856. case MSR_AMD64_OSVW_STATUS:
  1857. if (!guest_cpuid_has_osvw(vcpu))
  1858. return 1;
  1859. data = vcpu->arch.osvw.status;
  1860. break;
  1861. default:
  1862. if (kvm_pmu_msr(vcpu, msr))
  1863. return kvm_pmu_get_msr(vcpu, msr, pdata);
  1864. if (!ignore_msrs) {
  1865. vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
  1866. return 1;
  1867. } else {
  1868. vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
  1869. data = 0;
  1870. }
  1871. break;
  1872. }
  1873. *pdata = data;
  1874. return 0;
  1875. }
  1876. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  1877. /*
  1878. * Read or write a bunch of msrs. All parameters are kernel addresses.
  1879. *
  1880. * @return number of msrs set successfully.
  1881. */
  1882. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  1883. struct kvm_msr_entry *entries,
  1884. int (*do_msr)(struct kvm_vcpu *vcpu,
  1885. unsigned index, u64 *data))
  1886. {
  1887. int i, idx;
  1888. idx = srcu_read_lock(&vcpu->kvm->srcu);
  1889. for (i = 0; i < msrs->nmsrs; ++i)
  1890. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  1891. break;
  1892. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  1893. return i;
  1894. }
  1895. /*
  1896. * Read or write a bunch of msrs. Parameters are user addresses.
  1897. *
  1898. * @return number of msrs set successfully.
  1899. */
  1900. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  1901. int (*do_msr)(struct kvm_vcpu *vcpu,
  1902. unsigned index, u64 *data),
  1903. int writeback)
  1904. {
  1905. struct kvm_msrs msrs;
  1906. struct kvm_msr_entry *entries;
  1907. int r, n;
  1908. unsigned size;
  1909. r = -EFAULT;
  1910. if (copy_from_user(&msrs, user_msrs, sizeof msrs))
  1911. goto out;
  1912. r = -E2BIG;
  1913. if (msrs.nmsrs >= MAX_IO_MSRS)
  1914. goto out;
  1915. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  1916. entries = memdup_user(user_msrs->entries, size);
  1917. if (IS_ERR(entries)) {
  1918. r = PTR_ERR(entries);
  1919. goto out;
  1920. }
  1921. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  1922. if (r < 0)
  1923. goto out_free;
  1924. r = -EFAULT;
  1925. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  1926. goto out_free;
  1927. r = n;
  1928. out_free:
  1929. kfree(entries);
  1930. out:
  1931. return r;
  1932. }
  1933. int kvm_dev_ioctl_check_extension(long ext)
  1934. {
  1935. int r;
  1936. switch (ext) {
  1937. case KVM_CAP_IRQCHIP:
  1938. case KVM_CAP_HLT:
  1939. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  1940. case KVM_CAP_SET_TSS_ADDR:
  1941. case KVM_CAP_EXT_CPUID:
  1942. case KVM_CAP_CLOCKSOURCE:
  1943. case KVM_CAP_PIT:
  1944. case KVM_CAP_NOP_IO_DELAY:
  1945. case KVM_CAP_MP_STATE:
  1946. case KVM_CAP_SYNC_MMU:
  1947. case KVM_CAP_USER_NMI:
  1948. case KVM_CAP_REINJECT_CONTROL:
  1949. case KVM_CAP_IRQ_INJECT_STATUS:
  1950. case KVM_CAP_ASSIGN_DEV_IRQ:
  1951. case KVM_CAP_IRQFD:
  1952. case KVM_CAP_IOEVENTFD:
  1953. case KVM_CAP_PIT2:
  1954. case KVM_CAP_PIT_STATE2:
  1955. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  1956. case KVM_CAP_XEN_HVM:
  1957. case KVM_CAP_ADJUST_CLOCK:
  1958. case KVM_CAP_VCPU_EVENTS:
  1959. case KVM_CAP_HYPERV:
  1960. case KVM_CAP_HYPERV_VAPIC:
  1961. case KVM_CAP_HYPERV_SPIN:
  1962. case KVM_CAP_PCI_SEGMENT:
  1963. case KVM_CAP_DEBUGREGS:
  1964. case KVM_CAP_X86_ROBUST_SINGLESTEP:
  1965. case KVM_CAP_XSAVE:
  1966. case KVM_CAP_ASYNC_PF:
  1967. case KVM_CAP_GET_TSC_KHZ:
  1968. case KVM_CAP_PCI_2_3:
  1969. case KVM_CAP_KVMCLOCK_CTRL:
  1970. case KVM_CAP_READONLY_MEM:
  1971. case KVM_CAP_IRQFD_RESAMPLE:
  1972. r = 1;
  1973. break;
  1974. case KVM_CAP_COALESCED_MMIO:
  1975. r = KVM_COALESCED_MMIO_PAGE_OFFSET;
  1976. break;
  1977. case KVM_CAP_VAPIC:
  1978. r = !kvm_x86_ops->cpu_has_accelerated_tpr();
  1979. break;
  1980. case KVM_CAP_NR_VCPUS:
  1981. r = KVM_SOFT_MAX_VCPUS;
  1982. break;
  1983. case KVM_CAP_MAX_VCPUS:
  1984. r = KVM_MAX_VCPUS;
  1985. break;
  1986. case KVM_CAP_NR_MEMSLOTS:
  1987. r = KVM_MEMORY_SLOTS;
  1988. break;
  1989. case KVM_CAP_PV_MMU: /* obsolete */
  1990. r = 0;
  1991. break;
  1992. case KVM_CAP_IOMMU:
  1993. r = iommu_present(&pci_bus_type);
  1994. break;
  1995. case KVM_CAP_MCE:
  1996. r = KVM_MAX_MCE_BANKS;
  1997. break;
  1998. case KVM_CAP_XCRS:
  1999. r = cpu_has_xsave;
  2000. break;
  2001. case KVM_CAP_TSC_CONTROL:
  2002. r = kvm_has_tsc_control;
  2003. break;
  2004. case KVM_CAP_TSC_DEADLINE_TIMER:
  2005. r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
  2006. break;
  2007. default:
  2008. r = 0;
  2009. break;
  2010. }
  2011. return r;
  2012. }
  2013. long kvm_arch_dev_ioctl(struct file *filp,
  2014. unsigned int ioctl, unsigned long arg)
  2015. {
  2016. void __user *argp = (void __user *)arg;
  2017. long r;
  2018. switch (ioctl) {
  2019. case KVM_GET_MSR_INDEX_LIST: {
  2020. struct kvm_msr_list __user *user_msr_list = argp;
  2021. struct kvm_msr_list msr_list;
  2022. unsigned n;
  2023. r = -EFAULT;
  2024. if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
  2025. goto out;
  2026. n = msr_list.nmsrs;
  2027. msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
  2028. if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
  2029. goto out;
  2030. r = -E2BIG;
  2031. if (n < msr_list.nmsrs)
  2032. goto out;
  2033. r = -EFAULT;
  2034. if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  2035. num_msrs_to_save * sizeof(u32)))
  2036. goto out;
  2037. if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
  2038. &emulated_msrs,
  2039. ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
  2040. goto out;
  2041. r = 0;
  2042. break;
  2043. }
  2044. case KVM_GET_SUPPORTED_CPUID: {
  2045. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2046. struct kvm_cpuid2 cpuid;
  2047. r = -EFAULT;
  2048. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2049. goto out;
  2050. r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
  2051. cpuid_arg->entries);
  2052. if (r)
  2053. goto out;
  2054. r = -EFAULT;
  2055. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  2056. goto out;
  2057. r = 0;
  2058. break;
  2059. }
  2060. case KVM_X86_GET_MCE_CAP_SUPPORTED: {
  2061. u64 mce_cap;
  2062. mce_cap = KVM_MCE_CAP_SUPPORTED;
  2063. r = -EFAULT;
  2064. if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
  2065. goto out;
  2066. r = 0;
  2067. break;
  2068. }
  2069. default:
  2070. r = -EINVAL;
  2071. }
  2072. out:
  2073. return r;
  2074. }
  2075. static void wbinvd_ipi(void *garbage)
  2076. {
  2077. wbinvd();
  2078. }
  2079. static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  2080. {
  2081. return vcpu->kvm->arch.iommu_domain &&
  2082. !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
  2083. }
  2084. void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  2085. {
  2086. /* Address WBINVD may be executed by guest */
  2087. if (need_emulate_wbinvd(vcpu)) {
  2088. if (kvm_x86_ops->has_wbinvd_exit())
  2089. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  2090. else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  2091. smp_call_function_single(vcpu->cpu,
  2092. wbinvd_ipi, NULL, 1);
  2093. }
  2094. kvm_x86_ops->vcpu_load(vcpu, cpu);
  2095. /* Apply any externally detected TSC adjustments (due to suspend) */
  2096. if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
  2097. adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  2098. vcpu->arch.tsc_offset_adjustment = 0;
  2099. set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
  2100. }
  2101. if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
  2102. s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
  2103. native_read_tsc() - vcpu->arch.last_host_tsc;
  2104. if (tsc_delta < 0)
  2105. mark_tsc_unstable("KVM discovered backwards TSC");
  2106. if (check_tsc_unstable()) {
  2107. u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
  2108. vcpu->arch.last_guest_tsc);
  2109. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  2110. vcpu->arch.tsc_catchup = 1;
  2111. }
  2112. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2113. if (vcpu->cpu != cpu)
  2114. kvm_migrate_timers(vcpu);
  2115. vcpu->cpu = cpu;
  2116. }
  2117. accumulate_steal_time(vcpu);
  2118. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2119. }
  2120. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  2121. {
  2122. kvm_x86_ops->vcpu_put(vcpu);
  2123. kvm_put_guest_fpu(vcpu);
  2124. vcpu->arch.last_host_tsc = native_read_tsc();
  2125. }
  2126. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2127. struct kvm_lapic_state *s)
  2128. {
  2129. memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
  2130. return 0;
  2131. }
  2132. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2133. struct kvm_lapic_state *s)
  2134. {
  2135. kvm_apic_post_state_restore(vcpu, s);
  2136. update_cr8_intercept(vcpu);
  2137. return 0;
  2138. }
  2139. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2140. struct kvm_interrupt *irq)
  2141. {
  2142. if (irq->irq < 0 || irq->irq >= KVM_NR_INTERRUPTS)
  2143. return -EINVAL;
  2144. if (irqchip_in_kernel(vcpu->kvm))
  2145. return -ENXIO;
  2146. kvm_queue_interrupt(vcpu, irq->irq, false);
  2147. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2148. return 0;
  2149. }
  2150. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2151. {
  2152. kvm_inject_nmi(vcpu);
  2153. return 0;
  2154. }
  2155. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2156. struct kvm_tpr_access_ctl *tac)
  2157. {
  2158. if (tac->flags)
  2159. return -EINVAL;
  2160. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2161. return 0;
  2162. }
  2163. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2164. u64 mcg_cap)
  2165. {
  2166. int r;
  2167. unsigned bank_num = mcg_cap & 0xff, bank;
  2168. r = -EINVAL;
  2169. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2170. goto out;
  2171. if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
  2172. goto out;
  2173. r = 0;
  2174. vcpu->arch.mcg_cap = mcg_cap;
  2175. /* Init IA32_MCG_CTL to all 1s */
  2176. if (mcg_cap & MCG_CTL_P)
  2177. vcpu->arch.mcg_ctl = ~(u64)0;
  2178. /* Init IA32_MCi_CTL to all 1s */
  2179. for (bank = 0; bank < bank_num; bank++)
  2180. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2181. out:
  2182. return r;
  2183. }
  2184. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2185. struct kvm_x86_mce *mce)
  2186. {
  2187. u64 mcg_cap = vcpu->arch.mcg_cap;
  2188. unsigned bank_num = mcg_cap & 0xff;
  2189. u64 *banks = vcpu->arch.mce_banks;
  2190. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2191. return -EINVAL;
  2192. /*
  2193. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2194. * reporting is disabled
  2195. */
  2196. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2197. vcpu->arch.mcg_ctl != ~(u64)0)
  2198. return 0;
  2199. banks += 4 * mce->bank;
  2200. /*
  2201. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2202. * reporting is disabled for the bank
  2203. */
  2204. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2205. return 0;
  2206. if (mce->status & MCI_STATUS_UC) {
  2207. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2208. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2209. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2210. return 0;
  2211. }
  2212. if (banks[1] & MCI_STATUS_VAL)
  2213. mce->status |= MCI_STATUS_OVER;
  2214. banks[2] = mce->addr;
  2215. banks[3] = mce->misc;
  2216. vcpu->arch.mcg_status = mce->mcg_status;
  2217. banks[1] = mce->status;
  2218. kvm_queue_exception(vcpu, MC_VECTOR);
  2219. } else if (!(banks[1] & MCI_STATUS_VAL)
  2220. || !(banks[1] & MCI_STATUS_UC)) {
  2221. if (banks[1] & MCI_STATUS_VAL)
  2222. mce->status |= MCI_STATUS_OVER;
  2223. banks[2] = mce->addr;
  2224. banks[3] = mce->misc;
  2225. banks[1] = mce->status;
  2226. } else
  2227. banks[1] |= MCI_STATUS_OVER;
  2228. return 0;
  2229. }
  2230. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2231. struct kvm_vcpu_events *events)
  2232. {
  2233. process_nmi(vcpu);
  2234. events->exception.injected =
  2235. vcpu->arch.exception.pending &&
  2236. !kvm_exception_is_soft(vcpu->arch.exception.nr);
  2237. events->exception.nr = vcpu->arch.exception.nr;
  2238. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  2239. events->exception.pad = 0;
  2240. events->exception.error_code = vcpu->arch.exception.error_code;
  2241. events->interrupt.injected =
  2242. vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
  2243. events->interrupt.nr = vcpu->arch.interrupt.nr;
  2244. events->interrupt.soft = 0;
  2245. events->interrupt.shadow =
  2246. kvm_x86_ops->get_interrupt_shadow(vcpu,
  2247. KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
  2248. events->nmi.injected = vcpu->arch.nmi_injected;
  2249. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  2250. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  2251. events->nmi.pad = 0;
  2252. events->sipi_vector = vcpu->arch.sipi_vector;
  2253. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  2254. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2255. | KVM_VCPUEVENT_VALID_SHADOW);
  2256. memset(&events->reserved, 0, sizeof(events->reserved));
  2257. }
  2258. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  2259. struct kvm_vcpu_events *events)
  2260. {
  2261. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  2262. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2263. | KVM_VCPUEVENT_VALID_SHADOW))
  2264. return -EINVAL;
  2265. process_nmi(vcpu);
  2266. vcpu->arch.exception.pending = events->exception.injected;
  2267. vcpu->arch.exception.nr = events->exception.nr;
  2268. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  2269. vcpu->arch.exception.error_code = events->exception.error_code;
  2270. vcpu->arch.interrupt.pending = events->interrupt.injected;
  2271. vcpu->arch.interrupt.nr = events->interrupt.nr;
  2272. vcpu->arch.interrupt.soft = events->interrupt.soft;
  2273. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  2274. kvm_x86_ops->set_interrupt_shadow(vcpu,
  2275. events->interrupt.shadow);
  2276. vcpu->arch.nmi_injected = events->nmi.injected;
  2277. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  2278. vcpu->arch.nmi_pending = events->nmi.pending;
  2279. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  2280. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
  2281. vcpu->arch.sipi_vector = events->sipi_vector;
  2282. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2283. return 0;
  2284. }
  2285. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  2286. struct kvm_debugregs *dbgregs)
  2287. {
  2288. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  2289. dbgregs->dr6 = vcpu->arch.dr6;
  2290. dbgregs->dr7 = vcpu->arch.dr7;
  2291. dbgregs->flags = 0;
  2292. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  2293. }
  2294. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  2295. struct kvm_debugregs *dbgregs)
  2296. {
  2297. if (dbgregs->flags)
  2298. return -EINVAL;
  2299. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  2300. vcpu->arch.dr6 = dbgregs->dr6;
  2301. vcpu->arch.dr7 = dbgregs->dr7;
  2302. return 0;
  2303. }
  2304. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  2305. struct kvm_xsave *guest_xsave)
  2306. {
  2307. if (cpu_has_xsave)
  2308. memcpy(guest_xsave->region,
  2309. &vcpu->arch.guest_fpu.state->xsave,
  2310. xstate_size);
  2311. else {
  2312. memcpy(guest_xsave->region,
  2313. &vcpu->arch.guest_fpu.state->fxsave,
  2314. sizeof(struct i387_fxsave_struct));
  2315. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  2316. XSTATE_FPSSE;
  2317. }
  2318. }
  2319. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  2320. struct kvm_xsave *guest_xsave)
  2321. {
  2322. u64 xstate_bv =
  2323. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  2324. if (cpu_has_xsave)
  2325. memcpy(&vcpu->arch.guest_fpu.state->xsave,
  2326. guest_xsave->region, xstate_size);
  2327. else {
  2328. if (xstate_bv & ~XSTATE_FPSSE)
  2329. return -EINVAL;
  2330. memcpy(&vcpu->arch.guest_fpu.state->fxsave,
  2331. guest_xsave->region, sizeof(struct i387_fxsave_struct));
  2332. }
  2333. return 0;
  2334. }
  2335. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  2336. struct kvm_xcrs *guest_xcrs)
  2337. {
  2338. if (!cpu_has_xsave) {
  2339. guest_xcrs->nr_xcrs = 0;
  2340. return;
  2341. }
  2342. guest_xcrs->nr_xcrs = 1;
  2343. guest_xcrs->flags = 0;
  2344. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  2345. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  2346. }
  2347. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  2348. struct kvm_xcrs *guest_xcrs)
  2349. {
  2350. int i, r = 0;
  2351. if (!cpu_has_xsave)
  2352. return -EINVAL;
  2353. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  2354. return -EINVAL;
  2355. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  2356. /* Only support XCR0 currently */
  2357. if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
  2358. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  2359. guest_xcrs->xcrs[0].value);
  2360. break;
  2361. }
  2362. if (r)
  2363. r = -EINVAL;
  2364. return r;
  2365. }
  2366. /*
  2367. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  2368. * stopped by the hypervisor. This function will be called from the host only.
  2369. * EINVAL is returned when the host attempts to set the flag for a guest that
  2370. * does not support pv clocks.
  2371. */
  2372. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  2373. {
  2374. if (!vcpu->arch.time_page)
  2375. return -EINVAL;
  2376. vcpu->arch.pvclock_set_guest_stopped_request = true;
  2377. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2378. return 0;
  2379. }
  2380. long kvm_arch_vcpu_ioctl(struct file *filp,
  2381. unsigned int ioctl, unsigned long arg)
  2382. {
  2383. struct kvm_vcpu *vcpu = filp->private_data;
  2384. void __user *argp = (void __user *)arg;
  2385. int r;
  2386. union {
  2387. struct kvm_lapic_state *lapic;
  2388. struct kvm_xsave *xsave;
  2389. struct kvm_xcrs *xcrs;
  2390. void *buffer;
  2391. } u;
  2392. u.buffer = NULL;
  2393. switch (ioctl) {
  2394. case KVM_GET_LAPIC: {
  2395. r = -EINVAL;
  2396. if (!vcpu->arch.apic)
  2397. goto out;
  2398. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  2399. r = -ENOMEM;
  2400. if (!u.lapic)
  2401. goto out;
  2402. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  2403. if (r)
  2404. goto out;
  2405. r = -EFAULT;
  2406. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  2407. goto out;
  2408. r = 0;
  2409. break;
  2410. }
  2411. case KVM_SET_LAPIC: {
  2412. if (!vcpu->arch.apic)
  2413. goto out;
  2414. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  2415. if (IS_ERR(u.lapic))
  2416. return PTR_ERR(u.lapic);
  2417. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  2418. break;
  2419. }
  2420. case KVM_INTERRUPT: {
  2421. struct kvm_interrupt irq;
  2422. r = -EFAULT;
  2423. if (copy_from_user(&irq, argp, sizeof irq))
  2424. goto out;
  2425. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  2426. break;
  2427. }
  2428. case KVM_NMI: {
  2429. r = kvm_vcpu_ioctl_nmi(vcpu);
  2430. break;
  2431. }
  2432. case KVM_SET_CPUID: {
  2433. struct kvm_cpuid __user *cpuid_arg = argp;
  2434. struct kvm_cpuid cpuid;
  2435. r = -EFAULT;
  2436. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2437. goto out;
  2438. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  2439. break;
  2440. }
  2441. case KVM_SET_CPUID2: {
  2442. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2443. struct kvm_cpuid2 cpuid;
  2444. r = -EFAULT;
  2445. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2446. goto out;
  2447. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  2448. cpuid_arg->entries);
  2449. break;
  2450. }
  2451. case KVM_GET_CPUID2: {
  2452. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2453. struct kvm_cpuid2 cpuid;
  2454. r = -EFAULT;
  2455. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2456. goto out;
  2457. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  2458. cpuid_arg->entries);
  2459. if (r)
  2460. goto out;
  2461. r = -EFAULT;
  2462. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  2463. goto out;
  2464. r = 0;
  2465. break;
  2466. }
  2467. case KVM_GET_MSRS:
  2468. r = msr_io(vcpu, argp, kvm_get_msr, 1);
  2469. break;
  2470. case KVM_SET_MSRS:
  2471. r = msr_io(vcpu, argp, do_set_msr, 0);
  2472. break;
  2473. case KVM_TPR_ACCESS_REPORTING: {
  2474. struct kvm_tpr_access_ctl tac;
  2475. r = -EFAULT;
  2476. if (copy_from_user(&tac, argp, sizeof tac))
  2477. goto out;
  2478. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  2479. if (r)
  2480. goto out;
  2481. r = -EFAULT;
  2482. if (copy_to_user(argp, &tac, sizeof tac))
  2483. goto out;
  2484. r = 0;
  2485. break;
  2486. };
  2487. case KVM_SET_VAPIC_ADDR: {
  2488. struct kvm_vapic_addr va;
  2489. r = -EINVAL;
  2490. if (!irqchip_in_kernel(vcpu->kvm))
  2491. goto out;
  2492. r = -EFAULT;
  2493. if (copy_from_user(&va, argp, sizeof va))
  2494. goto out;
  2495. r = 0;
  2496. kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  2497. break;
  2498. }
  2499. case KVM_X86_SETUP_MCE: {
  2500. u64 mcg_cap;
  2501. r = -EFAULT;
  2502. if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  2503. goto out;
  2504. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  2505. break;
  2506. }
  2507. case KVM_X86_SET_MCE: {
  2508. struct kvm_x86_mce mce;
  2509. r = -EFAULT;
  2510. if (copy_from_user(&mce, argp, sizeof mce))
  2511. goto out;
  2512. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  2513. break;
  2514. }
  2515. case KVM_GET_VCPU_EVENTS: {
  2516. struct kvm_vcpu_events events;
  2517. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  2518. r = -EFAULT;
  2519. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  2520. break;
  2521. r = 0;
  2522. break;
  2523. }
  2524. case KVM_SET_VCPU_EVENTS: {
  2525. struct kvm_vcpu_events events;
  2526. r = -EFAULT;
  2527. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  2528. break;
  2529. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  2530. break;
  2531. }
  2532. case KVM_GET_DEBUGREGS: {
  2533. struct kvm_debugregs dbgregs;
  2534. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  2535. r = -EFAULT;
  2536. if (copy_to_user(argp, &dbgregs,
  2537. sizeof(struct kvm_debugregs)))
  2538. break;
  2539. r = 0;
  2540. break;
  2541. }
  2542. case KVM_SET_DEBUGREGS: {
  2543. struct kvm_debugregs dbgregs;
  2544. r = -EFAULT;
  2545. if (copy_from_user(&dbgregs, argp,
  2546. sizeof(struct kvm_debugregs)))
  2547. break;
  2548. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  2549. break;
  2550. }
  2551. case KVM_GET_XSAVE: {
  2552. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  2553. r = -ENOMEM;
  2554. if (!u.xsave)
  2555. break;
  2556. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  2557. r = -EFAULT;
  2558. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  2559. break;
  2560. r = 0;
  2561. break;
  2562. }
  2563. case KVM_SET_XSAVE: {
  2564. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  2565. if (IS_ERR(u.xsave))
  2566. return PTR_ERR(u.xsave);
  2567. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  2568. break;
  2569. }
  2570. case KVM_GET_XCRS: {
  2571. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  2572. r = -ENOMEM;
  2573. if (!u.xcrs)
  2574. break;
  2575. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  2576. r = -EFAULT;
  2577. if (copy_to_user(argp, u.xcrs,
  2578. sizeof(struct kvm_xcrs)))
  2579. break;
  2580. r = 0;
  2581. break;
  2582. }
  2583. case KVM_SET_XCRS: {
  2584. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  2585. if (IS_ERR(u.xcrs))
  2586. return PTR_ERR(u.xcrs);
  2587. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  2588. break;
  2589. }
  2590. case KVM_SET_TSC_KHZ: {
  2591. u32 user_tsc_khz;
  2592. r = -EINVAL;
  2593. user_tsc_khz = (u32)arg;
  2594. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  2595. goto out;
  2596. if (user_tsc_khz == 0)
  2597. user_tsc_khz = tsc_khz;
  2598. kvm_set_tsc_khz(vcpu, user_tsc_khz);
  2599. r = 0;
  2600. goto out;
  2601. }
  2602. case KVM_GET_TSC_KHZ: {
  2603. r = vcpu->arch.virtual_tsc_khz;
  2604. goto out;
  2605. }
  2606. case KVM_KVMCLOCK_CTRL: {
  2607. r = kvm_set_guest_paused(vcpu);
  2608. goto out;
  2609. }
  2610. default:
  2611. r = -EINVAL;
  2612. }
  2613. out:
  2614. kfree(u.buffer);
  2615. return r;
  2616. }
  2617. int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  2618. {
  2619. return VM_FAULT_SIGBUS;
  2620. }
  2621. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  2622. {
  2623. int ret;
  2624. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  2625. return -EINVAL;
  2626. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  2627. return ret;
  2628. }
  2629. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  2630. u64 ident_addr)
  2631. {
  2632. kvm->arch.ept_identity_map_addr = ident_addr;
  2633. return 0;
  2634. }
  2635. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  2636. u32 kvm_nr_mmu_pages)
  2637. {
  2638. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  2639. return -EINVAL;
  2640. mutex_lock(&kvm->slots_lock);
  2641. spin_lock(&kvm->mmu_lock);
  2642. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  2643. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  2644. spin_unlock(&kvm->mmu_lock);
  2645. mutex_unlock(&kvm->slots_lock);
  2646. return 0;
  2647. }
  2648. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  2649. {
  2650. return kvm->arch.n_max_mmu_pages;
  2651. }
  2652. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  2653. {
  2654. int r;
  2655. r = 0;
  2656. switch (chip->chip_id) {
  2657. case KVM_IRQCHIP_PIC_MASTER:
  2658. memcpy(&chip->chip.pic,
  2659. &pic_irqchip(kvm)->pics[0],
  2660. sizeof(struct kvm_pic_state));
  2661. break;
  2662. case KVM_IRQCHIP_PIC_SLAVE:
  2663. memcpy(&chip->chip.pic,
  2664. &pic_irqchip(kvm)->pics[1],
  2665. sizeof(struct kvm_pic_state));
  2666. break;
  2667. case KVM_IRQCHIP_IOAPIC:
  2668. r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
  2669. break;
  2670. default:
  2671. r = -EINVAL;
  2672. break;
  2673. }
  2674. return r;
  2675. }
  2676. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  2677. {
  2678. int r;
  2679. r = 0;
  2680. switch (chip->chip_id) {
  2681. case KVM_IRQCHIP_PIC_MASTER:
  2682. spin_lock(&pic_irqchip(kvm)->lock);
  2683. memcpy(&pic_irqchip(kvm)->pics[0],
  2684. &chip->chip.pic,
  2685. sizeof(struct kvm_pic_state));
  2686. spin_unlock(&pic_irqchip(kvm)->lock);
  2687. break;
  2688. case KVM_IRQCHIP_PIC_SLAVE:
  2689. spin_lock(&pic_irqchip(kvm)->lock);
  2690. memcpy(&pic_irqchip(kvm)->pics[1],
  2691. &chip->chip.pic,
  2692. sizeof(struct kvm_pic_state));
  2693. spin_unlock(&pic_irqchip(kvm)->lock);
  2694. break;
  2695. case KVM_IRQCHIP_IOAPIC:
  2696. r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
  2697. break;
  2698. default:
  2699. r = -EINVAL;
  2700. break;
  2701. }
  2702. kvm_pic_update_irq(pic_irqchip(kvm));
  2703. return r;
  2704. }
  2705. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  2706. {
  2707. int r = 0;
  2708. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2709. memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
  2710. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2711. return r;
  2712. }
  2713. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  2714. {
  2715. int r = 0;
  2716. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2717. memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
  2718. kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
  2719. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2720. return r;
  2721. }
  2722. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  2723. {
  2724. int r = 0;
  2725. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2726. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  2727. sizeof(ps->channels));
  2728. ps->flags = kvm->arch.vpit->pit_state.flags;
  2729. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2730. memset(&ps->reserved, 0, sizeof(ps->reserved));
  2731. return r;
  2732. }
  2733. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  2734. {
  2735. int r = 0, start = 0;
  2736. u32 prev_legacy, cur_legacy;
  2737. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2738. prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  2739. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  2740. if (!prev_legacy && cur_legacy)
  2741. start = 1;
  2742. memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
  2743. sizeof(kvm->arch.vpit->pit_state.channels));
  2744. kvm->arch.vpit->pit_state.flags = ps->flags;
  2745. kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
  2746. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2747. return r;
  2748. }
  2749. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  2750. struct kvm_reinject_control *control)
  2751. {
  2752. if (!kvm->arch.vpit)
  2753. return -ENXIO;
  2754. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2755. kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
  2756. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2757. return 0;
  2758. }
  2759. /**
  2760. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  2761. * @kvm: kvm instance
  2762. * @log: slot id and address to which we copy the log
  2763. *
  2764. * We need to keep it in mind that VCPU threads can write to the bitmap
  2765. * concurrently. So, to avoid losing data, we keep the following order for
  2766. * each bit:
  2767. *
  2768. * 1. Take a snapshot of the bit and clear it if needed.
  2769. * 2. Write protect the corresponding page.
  2770. * 3. Flush TLB's if needed.
  2771. * 4. Copy the snapshot to the userspace.
  2772. *
  2773. * Between 2 and 3, the guest may write to the page using the remaining TLB
  2774. * entry. This is not a problem because the page will be reported dirty at
  2775. * step 4 using the snapshot taken before and step 3 ensures that successive
  2776. * writes will be logged for the next call.
  2777. */
  2778. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  2779. {
  2780. int r;
  2781. struct kvm_memory_slot *memslot;
  2782. unsigned long n, i;
  2783. unsigned long *dirty_bitmap;
  2784. unsigned long *dirty_bitmap_buffer;
  2785. bool is_dirty = false;
  2786. mutex_lock(&kvm->slots_lock);
  2787. r = -EINVAL;
  2788. if (log->slot >= KVM_MEMORY_SLOTS)
  2789. goto out;
  2790. memslot = id_to_memslot(kvm->memslots, log->slot);
  2791. dirty_bitmap = memslot->dirty_bitmap;
  2792. r = -ENOENT;
  2793. if (!dirty_bitmap)
  2794. goto out;
  2795. n = kvm_dirty_bitmap_bytes(memslot);
  2796. dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
  2797. memset(dirty_bitmap_buffer, 0, n);
  2798. spin_lock(&kvm->mmu_lock);
  2799. for (i = 0; i < n / sizeof(long); i++) {
  2800. unsigned long mask;
  2801. gfn_t offset;
  2802. if (!dirty_bitmap[i])
  2803. continue;
  2804. is_dirty = true;
  2805. mask = xchg(&dirty_bitmap[i], 0);
  2806. dirty_bitmap_buffer[i] = mask;
  2807. offset = i * BITS_PER_LONG;
  2808. kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
  2809. }
  2810. if (is_dirty)
  2811. kvm_flush_remote_tlbs(kvm);
  2812. spin_unlock(&kvm->mmu_lock);
  2813. r = -EFAULT;
  2814. if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
  2815. goto out;
  2816. r = 0;
  2817. out:
  2818. mutex_unlock(&kvm->slots_lock);
  2819. return r;
  2820. }
  2821. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event)
  2822. {
  2823. if (!irqchip_in_kernel(kvm))
  2824. return -ENXIO;
  2825. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  2826. irq_event->irq, irq_event->level);
  2827. return 0;
  2828. }
  2829. long kvm_arch_vm_ioctl(struct file *filp,
  2830. unsigned int ioctl, unsigned long arg)
  2831. {
  2832. struct kvm *kvm = filp->private_data;
  2833. void __user *argp = (void __user *)arg;
  2834. int r = -ENOTTY;
  2835. /*
  2836. * This union makes it completely explicit to gcc-3.x
  2837. * that these two variables' stack usage should be
  2838. * combined, not added together.
  2839. */
  2840. union {
  2841. struct kvm_pit_state ps;
  2842. struct kvm_pit_state2 ps2;
  2843. struct kvm_pit_config pit_config;
  2844. } u;
  2845. switch (ioctl) {
  2846. case KVM_SET_TSS_ADDR:
  2847. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  2848. break;
  2849. case KVM_SET_IDENTITY_MAP_ADDR: {
  2850. u64 ident_addr;
  2851. r = -EFAULT;
  2852. if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  2853. goto out;
  2854. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  2855. break;
  2856. }
  2857. case KVM_SET_NR_MMU_PAGES:
  2858. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  2859. break;
  2860. case KVM_GET_NR_MMU_PAGES:
  2861. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  2862. break;
  2863. case KVM_CREATE_IRQCHIP: {
  2864. struct kvm_pic *vpic;
  2865. mutex_lock(&kvm->lock);
  2866. r = -EEXIST;
  2867. if (kvm->arch.vpic)
  2868. goto create_irqchip_unlock;
  2869. r = -EINVAL;
  2870. if (atomic_read(&kvm->online_vcpus))
  2871. goto create_irqchip_unlock;
  2872. r = -ENOMEM;
  2873. vpic = kvm_create_pic(kvm);
  2874. if (vpic) {
  2875. r = kvm_ioapic_init(kvm);
  2876. if (r) {
  2877. mutex_lock(&kvm->slots_lock);
  2878. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  2879. &vpic->dev_master);
  2880. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  2881. &vpic->dev_slave);
  2882. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  2883. &vpic->dev_eclr);
  2884. mutex_unlock(&kvm->slots_lock);
  2885. kfree(vpic);
  2886. goto create_irqchip_unlock;
  2887. }
  2888. } else
  2889. goto create_irqchip_unlock;
  2890. smp_wmb();
  2891. kvm->arch.vpic = vpic;
  2892. smp_wmb();
  2893. r = kvm_setup_default_irq_routing(kvm);
  2894. if (r) {
  2895. mutex_lock(&kvm->slots_lock);
  2896. mutex_lock(&kvm->irq_lock);
  2897. kvm_ioapic_destroy(kvm);
  2898. kvm_destroy_pic(kvm);
  2899. mutex_unlock(&kvm->irq_lock);
  2900. mutex_unlock(&kvm->slots_lock);
  2901. }
  2902. create_irqchip_unlock:
  2903. mutex_unlock(&kvm->lock);
  2904. break;
  2905. }
  2906. case KVM_CREATE_PIT:
  2907. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  2908. goto create_pit;
  2909. case KVM_CREATE_PIT2:
  2910. r = -EFAULT;
  2911. if (copy_from_user(&u.pit_config, argp,
  2912. sizeof(struct kvm_pit_config)))
  2913. goto out;
  2914. create_pit:
  2915. mutex_lock(&kvm->slots_lock);
  2916. r = -EEXIST;
  2917. if (kvm->arch.vpit)
  2918. goto create_pit_unlock;
  2919. r = -ENOMEM;
  2920. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  2921. if (kvm->arch.vpit)
  2922. r = 0;
  2923. create_pit_unlock:
  2924. mutex_unlock(&kvm->slots_lock);
  2925. break;
  2926. case KVM_GET_IRQCHIP: {
  2927. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  2928. struct kvm_irqchip *chip;
  2929. chip = memdup_user(argp, sizeof(*chip));
  2930. if (IS_ERR(chip)) {
  2931. r = PTR_ERR(chip);
  2932. goto out;
  2933. }
  2934. r = -ENXIO;
  2935. if (!irqchip_in_kernel(kvm))
  2936. goto get_irqchip_out;
  2937. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  2938. if (r)
  2939. goto get_irqchip_out;
  2940. r = -EFAULT;
  2941. if (copy_to_user(argp, chip, sizeof *chip))
  2942. goto get_irqchip_out;
  2943. r = 0;
  2944. get_irqchip_out:
  2945. kfree(chip);
  2946. break;
  2947. }
  2948. case KVM_SET_IRQCHIP: {
  2949. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  2950. struct kvm_irqchip *chip;
  2951. chip = memdup_user(argp, sizeof(*chip));
  2952. if (IS_ERR(chip)) {
  2953. r = PTR_ERR(chip);
  2954. goto out;
  2955. }
  2956. r = -ENXIO;
  2957. if (!irqchip_in_kernel(kvm))
  2958. goto set_irqchip_out;
  2959. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  2960. if (r)
  2961. goto set_irqchip_out;
  2962. r = 0;
  2963. set_irqchip_out:
  2964. kfree(chip);
  2965. break;
  2966. }
  2967. case KVM_GET_PIT: {
  2968. r = -EFAULT;
  2969. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  2970. goto out;
  2971. r = -ENXIO;
  2972. if (!kvm->arch.vpit)
  2973. goto out;
  2974. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  2975. if (r)
  2976. goto out;
  2977. r = -EFAULT;
  2978. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  2979. goto out;
  2980. r = 0;
  2981. break;
  2982. }
  2983. case KVM_SET_PIT: {
  2984. r = -EFAULT;
  2985. if (copy_from_user(&u.ps, argp, sizeof u.ps))
  2986. goto out;
  2987. r = -ENXIO;
  2988. if (!kvm->arch.vpit)
  2989. goto out;
  2990. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  2991. break;
  2992. }
  2993. case KVM_GET_PIT2: {
  2994. r = -ENXIO;
  2995. if (!kvm->arch.vpit)
  2996. goto out;
  2997. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  2998. if (r)
  2999. goto out;
  3000. r = -EFAULT;
  3001. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  3002. goto out;
  3003. r = 0;
  3004. break;
  3005. }
  3006. case KVM_SET_PIT2: {
  3007. r = -EFAULT;
  3008. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  3009. goto out;
  3010. r = -ENXIO;
  3011. if (!kvm->arch.vpit)
  3012. goto out;
  3013. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  3014. break;
  3015. }
  3016. case KVM_REINJECT_CONTROL: {
  3017. struct kvm_reinject_control control;
  3018. r = -EFAULT;
  3019. if (copy_from_user(&control, argp, sizeof(control)))
  3020. goto out;
  3021. r = kvm_vm_ioctl_reinject(kvm, &control);
  3022. break;
  3023. }
  3024. case KVM_XEN_HVM_CONFIG: {
  3025. r = -EFAULT;
  3026. if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
  3027. sizeof(struct kvm_xen_hvm_config)))
  3028. goto out;
  3029. r = -EINVAL;
  3030. if (kvm->arch.xen_hvm_config.flags)
  3031. goto out;
  3032. r = 0;
  3033. break;
  3034. }
  3035. case KVM_SET_CLOCK: {
  3036. struct kvm_clock_data user_ns;
  3037. u64 now_ns;
  3038. s64 delta;
  3039. r = -EFAULT;
  3040. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  3041. goto out;
  3042. r = -EINVAL;
  3043. if (user_ns.flags)
  3044. goto out;
  3045. r = 0;
  3046. local_irq_disable();
  3047. now_ns = get_kernel_ns();
  3048. delta = user_ns.clock - now_ns;
  3049. local_irq_enable();
  3050. kvm->arch.kvmclock_offset = delta;
  3051. break;
  3052. }
  3053. case KVM_GET_CLOCK: {
  3054. struct kvm_clock_data user_ns;
  3055. u64 now_ns;
  3056. local_irq_disable();
  3057. now_ns = get_kernel_ns();
  3058. user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
  3059. local_irq_enable();
  3060. user_ns.flags = 0;
  3061. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  3062. r = -EFAULT;
  3063. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  3064. goto out;
  3065. r = 0;
  3066. break;
  3067. }
  3068. default:
  3069. ;
  3070. }
  3071. out:
  3072. return r;
  3073. }
  3074. static void kvm_init_msr_list(void)
  3075. {
  3076. u32 dummy[2];
  3077. unsigned i, j;
  3078. /* skip the first msrs in the list. KVM-specific */
  3079. for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
  3080. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  3081. continue;
  3082. if (j < i)
  3083. msrs_to_save[j] = msrs_to_save[i];
  3084. j++;
  3085. }
  3086. num_msrs_to_save = j;
  3087. }
  3088. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  3089. const void *v)
  3090. {
  3091. int handled = 0;
  3092. int n;
  3093. do {
  3094. n = min(len, 8);
  3095. if (!(vcpu->arch.apic &&
  3096. !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
  3097. && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  3098. break;
  3099. handled += n;
  3100. addr += n;
  3101. len -= n;
  3102. v += n;
  3103. } while (len);
  3104. return handled;
  3105. }
  3106. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  3107. {
  3108. int handled = 0;
  3109. int n;
  3110. do {
  3111. n = min(len, 8);
  3112. if (!(vcpu->arch.apic &&
  3113. !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
  3114. && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  3115. break;
  3116. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
  3117. handled += n;
  3118. addr += n;
  3119. len -= n;
  3120. v += n;
  3121. } while (len);
  3122. return handled;
  3123. }
  3124. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  3125. struct kvm_segment *var, int seg)
  3126. {
  3127. kvm_x86_ops->set_segment(vcpu, var, seg);
  3128. }
  3129. void kvm_get_segment(struct kvm_vcpu *vcpu,
  3130. struct kvm_segment *var, int seg)
  3131. {
  3132. kvm_x86_ops->get_segment(vcpu, var, seg);
  3133. }
  3134. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
  3135. {
  3136. gpa_t t_gpa;
  3137. struct x86_exception exception;
  3138. BUG_ON(!mmu_is_nested(vcpu));
  3139. /* NPT walks are always user-walks */
  3140. access |= PFERR_USER_MASK;
  3141. t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
  3142. return t_gpa;
  3143. }
  3144. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  3145. struct x86_exception *exception)
  3146. {
  3147. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3148. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3149. }
  3150. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  3151. struct x86_exception *exception)
  3152. {
  3153. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3154. access |= PFERR_FETCH_MASK;
  3155. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3156. }
  3157. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  3158. struct x86_exception *exception)
  3159. {
  3160. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3161. access |= PFERR_WRITE_MASK;
  3162. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3163. }
  3164. /* uses this to access any guest's mapped memory without checking CPL */
  3165. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  3166. struct x86_exception *exception)
  3167. {
  3168. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  3169. }
  3170. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  3171. struct kvm_vcpu *vcpu, u32 access,
  3172. struct x86_exception *exception)
  3173. {
  3174. void *data = val;
  3175. int r = X86EMUL_CONTINUE;
  3176. while (bytes) {
  3177. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  3178. exception);
  3179. unsigned offset = addr & (PAGE_SIZE-1);
  3180. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  3181. int ret;
  3182. if (gpa == UNMAPPED_GVA)
  3183. return X86EMUL_PROPAGATE_FAULT;
  3184. ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
  3185. if (ret < 0) {
  3186. r = X86EMUL_IO_NEEDED;
  3187. goto out;
  3188. }
  3189. bytes -= toread;
  3190. data += toread;
  3191. addr += toread;
  3192. }
  3193. out:
  3194. return r;
  3195. }
  3196. /* used for instruction fetching */
  3197. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  3198. gva_t addr, void *val, unsigned int bytes,
  3199. struct x86_exception *exception)
  3200. {
  3201. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3202. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3203. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
  3204. access | PFERR_FETCH_MASK,
  3205. exception);
  3206. }
  3207. int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
  3208. gva_t addr, void *val, unsigned int bytes,
  3209. struct x86_exception *exception)
  3210. {
  3211. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3212. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3213. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  3214. exception);
  3215. }
  3216. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  3217. static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3218. gva_t addr, void *val, unsigned int bytes,
  3219. struct x86_exception *exception)
  3220. {
  3221. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3222. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
  3223. }
  3224. int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3225. gva_t addr, void *val,
  3226. unsigned int bytes,
  3227. struct x86_exception *exception)
  3228. {
  3229. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3230. void *data = val;
  3231. int r = X86EMUL_CONTINUE;
  3232. while (bytes) {
  3233. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  3234. PFERR_WRITE_MASK,
  3235. exception);
  3236. unsigned offset = addr & (PAGE_SIZE-1);
  3237. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  3238. int ret;
  3239. if (gpa == UNMAPPED_GVA)
  3240. return X86EMUL_PROPAGATE_FAULT;
  3241. ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
  3242. if (ret < 0) {
  3243. r = X86EMUL_IO_NEEDED;
  3244. goto out;
  3245. }
  3246. bytes -= towrite;
  3247. data += towrite;
  3248. addr += towrite;
  3249. }
  3250. out:
  3251. return r;
  3252. }
  3253. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  3254. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3255. gpa_t *gpa, struct x86_exception *exception,
  3256. bool write)
  3257. {
  3258. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  3259. | (write ? PFERR_WRITE_MASK : 0);
  3260. if (vcpu_match_mmio_gva(vcpu, gva)
  3261. && !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
  3262. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  3263. (gva & (PAGE_SIZE - 1));
  3264. trace_vcpu_match_mmio(gva, *gpa, write, false);
  3265. return 1;
  3266. }
  3267. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3268. if (*gpa == UNMAPPED_GVA)
  3269. return -1;
  3270. /* For APIC access vmexit */
  3271. if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3272. return 1;
  3273. if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
  3274. trace_vcpu_match_mmio(gva, *gpa, write, true);
  3275. return 1;
  3276. }
  3277. return 0;
  3278. }
  3279. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  3280. const void *val, int bytes)
  3281. {
  3282. int ret;
  3283. ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
  3284. if (ret < 0)
  3285. return 0;
  3286. kvm_mmu_pte_write(vcpu, gpa, val, bytes);
  3287. return 1;
  3288. }
  3289. struct read_write_emulator_ops {
  3290. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  3291. int bytes);
  3292. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3293. void *val, int bytes);
  3294. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3295. int bytes, void *val);
  3296. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3297. void *val, int bytes);
  3298. bool write;
  3299. };
  3300. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  3301. {
  3302. if (vcpu->mmio_read_completed) {
  3303. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  3304. vcpu->mmio_fragments[0].gpa, *(u64 *)val);
  3305. vcpu->mmio_read_completed = 0;
  3306. return 1;
  3307. }
  3308. return 0;
  3309. }
  3310. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3311. void *val, int bytes)
  3312. {
  3313. return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
  3314. }
  3315. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3316. void *val, int bytes)
  3317. {
  3318. return emulator_write_phys(vcpu, gpa, val, bytes);
  3319. }
  3320. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  3321. {
  3322. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
  3323. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  3324. }
  3325. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3326. void *val, int bytes)
  3327. {
  3328. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
  3329. return X86EMUL_IO_NEEDED;
  3330. }
  3331. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3332. void *val, int bytes)
  3333. {
  3334. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  3335. memcpy(vcpu->run->mmio.data, frag->data, frag->len);
  3336. return X86EMUL_CONTINUE;
  3337. }
  3338. static const struct read_write_emulator_ops read_emultor = {
  3339. .read_write_prepare = read_prepare,
  3340. .read_write_emulate = read_emulate,
  3341. .read_write_mmio = vcpu_mmio_read,
  3342. .read_write_exit_mmio = read_exit_mmio,
  3343. };
  3344. static const struct read_write_emulator_ops write_emultor = {
  3345. .read_write_emulate = write_emulate,
  3346. .read_write_mmio = write_mmio,
  3347. .read_write_exit_mmio = write_exit_mmio,
  3348. .write = true,
  3349. };
  3350. static int emulator_read_write_onepage(unsigned long addr, void *val,
  3351. unsigned int bytes,
  3352. struct x86_exception *exception,
  3353. struct kvm_vcpu *vcpu,
  3354. const struct read_write_emulator_ops *ops)
  3355. {
  3356. gpa_t gpa;
  3357. int handled, ret;
  3358. bool write = ops->write;
  3359. struct kvm_mmio_fragment *frag;
  3360. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  3361. if (ret < 0)
  3362. return X86EMUL_PROPAGATE_FAULT;
  3363. /* For APIC access vmexit */
  3364. if (ret)
  3365. goto mmio;
  3366. if (ops->read_write_emulate(vcpu, gpa, val, bytes))
  3367. return X86EMUL_CONTINUE;
  3368. mmio:
  3369. /*
  3370. * Is this MMIO handled locally?
  3371. */
  3372. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  3373. if (handled == bytes)
  3374. return X86EMUL_CONTINUE;
  3375. gpa += handled;
  3376. bytes -= handled;
  3377. val += handled;
  3378. while (bytes) {
  3379. unsigned now = min(bytes, 8U);
  3380. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  3381. frag->gpa = gpa;
  3382. frag->data = val;
  3383. frag->len = now;
  3384. gpa += now;
  3385. val += now;
  3386. bytes -= now;
  3387. }
  3388. return X86EMUL_CONTINUE;
  3389. }
  3390. int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
  3391. void *val, unsigned int bytes,
  3392. struct x86_exception *exception,
  3393. const struct read_write_emulator_ops *ops)
  3394. {
  3395. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3396. gpa_t gpa;
  3397. int rc;
  3398. if (ops->read_write_prepare &&
  3399. ops->read_write_prepare(vcpu, val, bytes))
  3400. return X86EMUL_CONTINUE;
  3401. vcpu->mmio_nr_fragments = 0;
  3402. /* Crossing a page boundary? */
  3403. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  3404. int now;
  3405. now = -addr & ~PAGE_MASK;
  3406. rc = emulator_read_write_onepage(addr, val, now, exception,
  3407. vcpu, ops);
  3408. if (rc != X86EMUL_CONTINUE)
  3409. return rc;
  3410. addr += now;
  3411. val += now;
  3412. bytes -= now;
  3413. }
  3414. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  3415. vcpu, ops);
  3416. if (rc != X86EMUL_CONTINUE)
  3417. return rc;
  3418. if (!vcpu->mmio_nr_fragments)
  3419. return rc;
  3420. gpa = vcpu->mmio_fragments[0].gpa;
  3421. vcpu->mmio_needed = 1;
  3422. vcpu->mmio_cur_fragment = 0;
  3423. vcpu->run->mmio.len = vcpu->mmio_fragments[0].len;
  3424. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  3425. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  3426. vcpu->run->mmio.phys_addr = gpa;
  3427. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  3428. }
  3429. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  3430. unsigned long addr,
  3431. void *val,
  3432. unsigned int bytes,
  3433. struct x86_exception *exception)
  3434. {
  3435. return emulator_read_write(ctxt, addr, val, bytes,
  3436. exception, &read_emultor);
  3437. }
  3438. int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  3439. unsigned long addr,
  3440. const void *val,
  3441. unsigned int bytes,
  3442. struct x86_exception *exception)
  3443. {
  3444. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  3445. exception, &write_emultor);
  3446. }
  3447. #define CMPXCHG_TYPE(t, ptr, old, new) \
  3448. (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  3449. #ifdef CONFIG_X86_64
  3450. # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  3451. #else
  3452. # define CMPXCHG64(ptr, old, new) \
  3453. (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
  3454. #endif
  3455. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  3456. unsigned long addr,
  3457. const void *old,
  3458. const void *new,
  3459. unsigned int bytes,
  3460. struct x86_exception *exception)
  3461. {
  3462. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3463. gpa_t gpa;
  3464. struct page *page;
  3465. char *kaddr;
  3466. bool exchanged;
  3467. /* guests cmpxchg8b have to be emulated atomically */
  3468. if (bytes > 8 || (bytes & (bytes - 1)))
  3469. goto emul_write;
  3470. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  3471. if (gpa == UNMAPPED_GVA ||
  3472. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3473. goto emul_write;
  3474. if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  3475. goto emul_write;
  3476. page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  3477. if (is_error_page(page))
  3478. goto emul_write;
  3479. kaddr = kmap_atomic(page);
  3480. kaddr += offset_in_page(gpa);
  3481. switch (bytes) {
  3482. case 1:
  3483. exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  3484. break;
  3485. case 2:
  3486. exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  3487. break;
  3488. case 4:
  3489. exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  3490. break;
  3491. case 8:
  3492. exchanged = CMPXCHG64(kaddr, old, new);
  3493. break;
  3494. default:
  3495. BUG();
  3496. }
  3497. kunmap_atomic(kaddr);
  3498. kvm_release_page_dirty(page);
  3499. if (!exchanged)
  3500. return X86EMUL_CMPXCHG_FAILED;
  3501. kvm_mmu_pte_write(vcpu, gpa, new, bytes);
  3502. return X86EMUL_CONTINUE;
  3503. emul_write:
  3504. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  3505. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  3506. }
  3507. static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  3508. {
  3509. /* TODO: String I/O for in kernel device */
  3510. int r;
  3511. if (vcpu->arch.pio.in)
  3512. r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
  3513. vcpu->arch.pio.size, pd);
  3514. else
  3515. r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
  3516. vcpu->arch.pio.port, vcpu->arch.pio.size,
  3517. pd);
  3518. return r;
  3519. }
  3520. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  3521. unsigned short port, void *val,
  3522. unsigned int count, bool in)
  3523. {
  3524. trace_kvm_pio(!in, port, size, count);
  3525. vcpu->arch.pio.port = port;
  3526. vcpu->arch.pio.in = in;
  3527. vcpu->arch.pio.count = count;
  3528. vcpu->arch.pio.size = size;
  3529. if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
  3530. vcpu->arch.pio.count = 0;
  3531. return 1;
  3532. }
  3533. vcpu->run->exit_reason = KVM_EXIT_IO;
  3534. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  3535. vcpu->run->io.size = size;
  3536. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  3537. vcpu->run->io.count = count;
  3538. vcpu->run->io.port = port;
  3539. return 0;
  3540. }
  3541. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  3542. int size, unsigned short port, void *val,
  3543. unsigned int count)
  3544. {
  3545. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3546. int ret;
  3547. if (vcpu->arch.pio.count)
  3548. goto data_avail;
  3549. ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  3550. if (ret) {
  3551. data_avail:
  3552. memcpy(val, vcpu->arch.pio_data, size * count);
  3553. vcpu->arch.pio.count = 0;
  3554. return 1;
  3555. }
  3556. return 0;
  3557. }
  3558. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  3559. int size, unsigned short port,
  3560. const void *val, unsigned int count)
  3561. {
  3562. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3563. memcpy(vcpu->arch.pio_data, val, size * count);
  3564. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  3565. }
  3566. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  3567. {
  3568. return kvm_x86_ops->get_segment_base(vcpu, seg);
  3569. }
  3570. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  3571. {
  3572. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  3573. }
  3574. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  3575. {
  3576. if (!need_emulate_wbinvd(vcpu))
  3577. return X86EMUL_CONTINUE;
  3578. if (kvm_x86_ops->has_wbinvd_exit()) {
  3579. int cpu = get_cpu();
  3580. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  3581. smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  3582. wbinvd_ipi, NULL, 1);
  3583. put_cpu();
  3584. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  3585. } else
  3586. wbinvd();
  3587. return X86EMUL_CONTINUE;
  3588. }
  3589. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  3590. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  3591. {
  3592. kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
  3593. }
  3594. int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
  3595. {
  3596. return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  3597. }
  3598. int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
  3599. {
  3600. return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  3601. }
  3602. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  3603. {
  3604. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  3605. }
  3606. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  3607. {
  3608. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3609. unsigned long value;
  3610. switch (cr) {
  3611. case 0:
  3612. value = kvm_read_cr0(vcpu);
  3613. break;
  3614. case 2:
  3615. value = vcpu->arch.cr2;
  3616. break;
  3617. case 3:
  3618. value = kvm_read_cr3(vcpu);
  3619. break;
  3620. case 4:
  3621. value = kvm_read_cr4(vcpu);
  3622. break;
  3623. case 8:
  3624. value = kvm_get_cr8(vcpu);
  3625. break;
  3626. default:
  3627. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  3628. return 0;
  3629. }
  3630. return value;
  3631. }
  3632. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  3633. {
  3634. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3635. int res = 0;
  3636. switch (cr) {
  3637. case 0:
  3638. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  3639. break;
  3640. case 2:
  3641. vcpu->arch.cr2 = val;
  3642. break;
  3643. case 3:
  3644. res = kvm_set_cr3(vcpu, val);
  3645. break;
  3646. case 4:
  3647. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  3648. break;
  3649. case 8:
  3650. res = kvm_set_cr8(vcpu, val);
  3651. break;
  3652. default:
  3653. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  3654. res = -1;
  3655. }
  3656. return res;
  3657. }
  3658. static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
  3659. {
  3660. kvm_set_rflags(emul_to_vcpu(ctxt), val);
  3661. }
  3662. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  3663. {
  3664. return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
  3665. }
  3666. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3667. {
  3668. kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
  3669. }
  3670. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3671. {
  3672. kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
  3673. }
  3674. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3675. {
  3676. kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  3677. }
  3678. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3679. {
  3680. kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  3681. }
  3682. static unsigned long emulator_get_cached_segment_base(
  3683. struct x86_emulate_ctxt *ctxt, int seg)
  3684. {
  3685. return get_segment_base(emul_to_vcpu(ctxt), seg);
  3686. }
  3687. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  3688. struct desc_struct *desc, u32 *base3,
  3689. int seg)
  3690. {
  3691. struct kvm_segment var;
  3692. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  3693. *selector = var.selector;
  3694. if (var.unusable)
  3695. return false;
  3696. if (var.g)
  3697. var.limit >>= 12;
  3698. set_desc_limit(desc, var.limit);
  3699. set_desc_base(desc, (unsigned long)var.base);
  3700. #ifdef CONFIG_X86_64
  3701. if (base3)
  3702. *base3 = var.base >> 32;
  3703. #endif
  3704. desc->type = var.type;
  3705. desc->s = var.s;
  3706. desc->dpl = var.dpl;
  3707. desc->p = var.present;
  3708. desc->avl = var.avl;
  3709. desc->l = var.l;
  3710. desc->d = var.db;
  3711. desc->g = var.g;
  3712. return true;
  3713. }
  3714. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  3715. struct desc_struct *desc, u32 base3,
  3716. int seg)
  3717. {
  3718. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3719. struct kvm_segment var;
  3720. var.selector = selector;
  3721. var.base = get_desc_base(desc);
  3722. #ifdef CONFIG_X86_64
  3723. var.base |= ((u64)base3) << 32;
  3724. #endif
  3725. var.limit = get_desc_limit(desc);
  3726. if (desc->g)
  3727. var.limit = (var.limit << 12) | 0xfff;
  3728. var.type = desc->type;
  3729. var.present = desc->p;
  3730. var.dpl = desc->dpl;
  3731. var.db = desc->d;
  3732. var.s = desc->s;
  3733. var.l = desc->l;
  3734. var.g = desc->g;
  3735. var.avl = desc->avl;
  3736. var.present = desc->p;
  3737. var.unusable = !var.present;
  3738. var.padding = 0;
  3739. kvm_set_segment(vcpu, &var, seg);
  3740. return;
  3741. }
  3742. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  3743. u32 msr_index, u64 *pdata)
  3744. {
  3745. return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
  3746. }
  3747. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  3748. u32 msr_index, u64 data)
  3749. {
  3750. return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
  3751. }
  3752. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  3753. u32 pmc, u64 *pdata)
  3754. {
  3755. return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
  3756. }
  3757. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  3758. {
  3759. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  3760. }
  3761. static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
  3762. {
  3763. preempt_disable();
  3764. kvm_load_guest_fpu(emul_to_vcpu(ctxt));
  3765. /*
  3766. * CR0.TS may reference the host fpu state, not the guest fpu state,
  3767. * so it may be clear at this point.
  3768. */
  3769. clts();
  3770. }
  3771. static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
  3772. {
  3773. preempt_enable();
  3774. }
  3775. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  3776. struct x86_instruction_info *info,
  3777. enum x86_intercept_stage stage)
  3778. {
  3779. return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
  3780. }
  3781. static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  3782. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
  3783. {
  3784. kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
  3785. }
  3786. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  3787. {
  3788. return kvm_register_read(emul_to_vcpu(ctxt), reg);
  3789. }
  3790. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  3791. {
  3792. kvm_register_write(emul_to_vcpu(ctxt), reg, val);
  3793. }
  3794. static const struct x86_emulate_ops emulate_ops = {
  3795. .read_gpr = emulator_read_gpr,
  3796. .write_gpr = emulator_write_gpr,
  3797. .read_std = kvm_read_guest_virt_system,
  3798. .write_std = kvm_write_guest_virt_system,
  3799. .fetch = kvm_fetch_guest_virt,
  3800. .read_emulated = emulator_read_emulated,
  3801. .write_emulated = emulator_write_emulated,
  3802. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  3803. .invlpg = emulator_invlpg,
  3804. .pio_in_emulated = emulator_pio_in_emulated,
  3805. .pio_out_emulated = emulator_pio_out_emulated,
  3806. .get_segment = emulator_get_segment,
  3807. .set_segment = emulator_set_segment,
  3808. .get_cached_segment_base = emulator_get_cached_segment_base,
  3809. .get_gdt = emulator_get_gdt,
  3810. .get_idt = emulator_get_idt,
  3811. .set_gdt = emulator_set_gdt,
  3812. .set_idt = emulator_set_idt,
  3813. .get_cr = emulator_get_cr,
  3814. .set_cr = emulator_set_cr,
  3815. .set_rflags = emulator_set_rflags,
  3816. .cpl = emulator_get_cpl,
  3817. .get_dr = emulator_get_dr,
  3818. .set_dr = emulator_set_dr,
  3819. .set_msr = emulator_set_msr,
  3820. .get_msr = emulator_get_msr,
  3821. .read_pmc = emulator_read_pmc,
  3822. .halt = emulator_halt,
  3823. .wbinvd = emulator_wbinvd,
  3824. .fix_hypercall = emulator_fix_hypercall,
  3825. .get_fpu = emulator_get_fpu,
  3826. .put_fpu = emulator_put_fpu,
  3827. .intercept = emulator_intercept,
  3828. .get_cpuid = emulator_get_cpuid,
  3829. };
  3830. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  3831. {
  3832. u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
  3833. /*
  3834. * an sti; sti; sequence only disable interrupts for the first
  3835. * instruction. So, if the last instruction, be it emulated or
  3836. * not, left the system with the INT_STI flag enabled, it
  3837. * means that the last instruction is an sti. We should not
  3838. * leave the flag on in this case. The same goes for mov ss
  3839. */
  3840. if (!(int_shadow & mask))
  3841. kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  3842. }
  3843. static void inject_emulated_exception(struct kvm_vcpu *vcpu)
  3844. {
  3845. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  3846. if (ctxt->exception.vector == PF_VECTOR)
  3847. kvm_propagate_fault(vcpu, &ctxt->exception);
  3848. else if (ctxt->exception.error_code_valid)
  3849. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  3850. ctxt->exception.error_code);
  3851. else
  3852. kvm_queue_exception(vcpu, ctxt->exception.vector);
  3853. }
  3854. static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
  3855. {
  3856. memset(&ctxt->twobyte, 0,
  3857. (void *)&ctxt->_regs - (void *)&ctxt->twobyte);
  3858. ctxt->fetch.start = 0;
  3859. ctxt->fetch.end = 0;
  3860. ctxt->io_read.pos = 0;
  3861. ctxt->io_read.end = 0;
  3862. ctxt->mem_read.pos = 0;
  3863. ctxt->mem_read.end = 0;
  3864. }
  3865. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  3866. {
  3867. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  3868. int cs_db, cs_l;
  3869. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  3870. ctxt->eflags = kvm_get_rflags(vcpu);
  3871. ctxt->eip = kvm_rip_read(vcpu);
  3872. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  3873. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  3874. cs_l ? X86EMUL_MODE_PROT64 :
  3875. cs_db ? X86EMUL_MODE_PROT32 :
  3876. X86EMUL_MODE_PROT16;
  3877. ctxt->guest_mode = is_guest_mode(vcpu);
  3878. init_decode_cache(ctxt);
  3879. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  3880. }
  3881. int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  3882. {
  3883. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  3884. int ret;
  3885. init_emulate_ctxt(vcpu);
  3886. ctxt->op_bytes = 2;
  3887. ctxt->ad_bytes = 2;
  3888. ctxt->_eip = ctxt->eip + inc_eip;
  3889. ret = emulate_int_real(ctxt, irq);
  3890. if (ret != X86EMUL_CONTINUE)
  3891. return EMULATE_FAIL;
  3892. ctxt->eip = ctxt->_eip;
  3893. kvm_rip_write(vcpu, ctxt->eip);
  3894. kvm_set_rflags(vcpu, ctxt->eflags);
  3895. if (irq == NMI_VECTOR)
  3896. vcpu->arch.nmi_pending = 0;
  3897. else
  3898. vcpu->arch.interrupt.pending = false;
  3899. return EMULATE_DONE;
  3900. }
  3901. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  3902. static int handle_emulation_failure(struct kvm_vcpu *vcpu)
  3903. {
  3904. int r = EMULATE_DONE;
  3905. ++vcpu->stat.insn_emulation_fail;
  3906. trace_kvm_emulate_insn_failed(vcpu);
  3907. if (!is_guest_mode(vcpu)) {
  3908. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  3909. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  3910. vcpu->run->internal.ndata = 0;
  3911. r = EMULATE_FAIL;
  3912. }
  3913. kvm_queue_exception(vcpu, UD_VECTOR);
  3914. return r;
  3915. }
  3916. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
  3917. {
  3918. gpa_t gpa;
  3919. pfn_t pfn;
  3920. if (tdp_enabled)
  3921. return false;
  3922. /*
  3923. * if emulation was due to access to shadowed page table
  3924. * and it failed try to unshadow page and re-enter the
  3925. * guest to let CPU execute the instruction.
  3926. */
  3927. if (kvm_mmu_unprotect_page_virt(vcpu, gva))
  3928. return true;
  3929. gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
  3930. if (gpa == UNMAPPED_GVA)
  3931. return true; /* let cpu generate fault */
  3932. /*
  3933. * Do not retry the unhandleable instruction if it faults on the
  3934. * readonly host memory, otherwise it will goto a infinite loop:
  3935. * retry instruction -> write #PF -> emulation fail -> retry
  3936. * instruction -> ...
  3937. */
  3938. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  3939. if (!is_error_noslot_pfn(pfn)) {
  3940. kvm_release_pfn_clean(pfn);
  3941. return true;
  3942. }
  3943. return false;
  3944. }
  3945. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  3946. unsigned long cr2, int emulation_type)
  3947. {
  3948. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3949. unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  3950. last_retry_eip = vcpu->arch.last_retry_eip;
  3951. last_retry_addr = vcpu->arch.last_retry_addr;
  3952. /*
  3953. * If the emulation is caused by #PF and it is non-page_table
  3954. * writing instruction, it means the VM-EXIT is caused by shadow
  3955. * page protected, we can zap the shadow page and retry this
  3956. * instruction directly.
  3957. *
  3958. * Note: if the guest uses a non-page-table modifying instruction
  3959. * on the PDE that points to the instruction, then we will unmap
  3960. * the instruction and go to an infinite loop. So, we cache the
  3961. * last retried eip and the last fault address, if we meet the eip
  3962. * and the address again, we can break out of the potential infinite
  3963. * loop.
  3964. */
  3965. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  3966. if (!(emulation_type & EMULTYPE_RETRY))
  3967. return false;
  3968. if (x86_page_table_writing_insn(ctxt))
  3969. return false;
  3970. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  3971. return false;
  3972. vcpu->arch.last_retry_eip = ctxt->eip;
  3973. vcpu->arch.last_retry_addr = cr2;
  3974. if (!vcpu->arch.mmu.direct_map)
  3975. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  3976. kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  3977. return true;
  3978. }
  3979. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  3980. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  3981. int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  3982. unsigned long cr2,
  3983. int emulation_type,
  3984. void *insn,
  3985. int insn_len)
  3986. {
  3987. int r;
  3988. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  3989. bool writeback = true;
  3990. kvm_clear_exception_queue(vcpu);
  3991. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  3992. init_emulate_ctxt(vcpu);
  3993. ctxt->interruptibility = 0;
  3994. ctxt->have_exception = false;
  3995. ctxt->perm_ok = false;
  3996. ctxt->only_vendor_specific_insn
  3997. = emulation_type & EMULTYPE_TRAP_UD;
  3998. r = x86_decode_insn(ctxt, insn, insn_len);
  3999. trace_kvm_emulate_insn_start(vcpu);
  4000. ++vcpu->stat.insn_emulation;
  4001. if (r != EMULATION_OK) {
  4002. if (emulation_type & EMULTYPE_TRAP_UD)
  4003. return EMULATE_FAIL;
  4004. if (reexecute_instruction(vcpu, cr2))
  4005. return EMULATE_DONE;
  4006. if (emulation_type & EMULTYPE_SKIP)
  4007. return EMULATE_FAIL;
  4008. return handle_emulation_failure(vcpu);
  4009. }
  4010. }
  4011. if (emulation_type & EMULTYPE_SKIP) {
  4012. kvm_rip_write(vcpu, ctxt->_eip);
  4013. return EMULATE_DONE;
  4014. }
  4015. if (retry_instruction(ctxt, cr2, emulation_type))
  4016. return EMULATE_DONE;
  4017. /* this is needed for vmware backdoor interface to work since it
  4018. changes registers values during IO operation */
  4019. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  4020. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  4021. emulator_invalidate_register_cache(ctxt);
  4022. }
  4023. restart:
  4024. r = x86_emulate_insn(ctxt);
  4025. if (r == EMULATION_INTERCEPTED)
  4026. return EMULATE_DONE;
  4027. if (r == EMULATION_FAILED) {
  4028. if (reexecute_instruction(vcpu, cr2))
  4029. return EMULATE_DONE;
  4030. return handle_emulation_failure(vcpu);
  4031. }
  4032. if (ctxt->have_exception) {
  4033. inject_emulated_exception(vcpu);
  4034. r = EMULATE_DONE;
  4035. } else if (vcpu->arch.pio.count) {
  4036. if (!vcpu->arch.pio.in)
  4037. vcpu->arch.pio.count = 0;
  4038. else {
  4039. writeback = false;
  4040. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  4041. }
  4042. r = EMULATE_DO_MMIO;
  4043. } else if (vcpu->mmio_needed) {
  4044. if (!vcpu->mmio_is_write)
  4045. writeback = false;
  4046. r = EMULATE_DO_MMIO;
  4047. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  4048. } else if (r == EMULATION_RESTART)
  4049. goto restart;
  4050. else
  4051. r = EMULATE_DONE;
  4052. if (writeback) {
  4053. toggle_interruptibility(vcpu, ctxt->interruptibility);
  4054. kvm_set_rflags(vcpu, ctxt->eflags);
  4055. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4056. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  4057. kvm_rip_write(vcpu, ctxt->eip);
  4058. } else
  4059. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  4060. return r;
  4061. }
  4062. EXPORT_SYMBOL_GPL(x86_emulate_instruction);
  4063. int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
  4064. {
  4065. unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4066. int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  4067. size, port, &val, 1);
  4068. /* do not return to emulator after return from userspace */
  4069. vcpu->arch.pio.count = 0;
  4070. return ret;
  4071. }
  4072. EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
  4073. static void tsc_bad(void *info)
  4074. {
  4075. __this_cpu_write(cpu_tsc_khz, 0);
  4076. }
  4077. static void tsc_khz_changed(void *data)
  4078. {
  4079. struct cpufreq_freqs *freq = data;
  4080. unsigned long khz = 0;
  4081. if (data)
  4082. khz = freq->new;
  4083. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  4084. khz = cpufreq_quick_get(raw_smp_processor_id());
  4085. if (!khz)
  4086. khz = tsc_khz;
  4087. __this_cpu_write(cpu_tsc_khz, khz);
  4088. }
  4089. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  4090. void *data)
  4091. {
  4092. struct cpufreq_freqs *freq = data;
  4093. struct kvm *kvm;
  4094. struct kvm_vcpu *vcpu;
  4095. int i, send_ipi = 0;
  4096. /*
  4097. * We allow guests to temporarily run on slowing clocks,
  4098. * provided we notify them after, or to run on accelerating
  4099. * clocks, provided we notify them before. Thus time never
  4100. * goes backwards.
  4101. *
  4102. * However, we have a problem. We can't atomically update
  4103. * the frequency of a given CPU from this function; it is
  4104. * merely a notifier, which can be called from any CPU.
  4105. * Changing the TSC frequency at arbitrary points in time
  4106. * requires a recomputation of local variables related to
  4107. * the TSC for each VCPU. We must flag these local variables
  4108. * to be updated and be sure the update takes place with the
  4109. * new frequency before any guests proceed.
  4110. *
  4111. * Unfortunately, the combination of hotplug CPU and frequency
  4112. * change creates an intractable locking scenario; the order
  4113. * of when these callouts happen is undefined with respect to
  4114. * CPU hotplug, and they can race with each other. As such,
  4115. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  4116. * undefined; you can actually have a CPU frequency change take
  4117. * place in between the computation of X and the setting of the
  4118. * variable. To protect against this problem, all updates of
  4119. * the per_cpu tsc_khz variable are done in an interrupt
  4120. * protected IPI, and all callers wishing to update the value
  4121. * must wait for a synchronous IPI to complete (which is trivial
  4122. * if the caller is on the CPU already). This establishes the
  4123. * necessary total order on variable updates.
  4124. *
  4125. * Note that because a guest time update may take place
  4126. * anytime after the setting of the VCPU's request bit, the
  4127. * correct TSC value must be set before the request. However,
  4128. * to ensure the update actually makes it to any guest which
  4129. * starts running in hardware virtualization between the set
  4130. * and the acquisition of the spinlock, we must also ping the
  4131. * CPU after setting the request bit.
  4132. *
  4133. */
  4134. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  4135. return 0;
  4136. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  4137. return 0;
  4138. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  4139. raw_spin_lock(&kvm_lock);
  4140. list_for_each_entry(kvm, &vm_list, vm_list) {
  4141. kvm_for_each_vcpu(i, vcpu, kvm) {
  4142. if (vcpu->cpu != freq->cpu)
  4143. continue;
  4144. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  4145. if (vcpu->cpu != smp_processor_id())
  4146. send_ipi = 1;
  4147. }
  4148. }
  4149. raw_spin_unlock(&kvm_lock);
  4150. if (freq->old < freq->new && send_ipi) {
  4151. /*
  4152. * We upscale the frequency. Must make the guest
  4153. * doesn't see old kvmclock values while running with
  4154. * the new frequency, otherwise we risk the guest sees
  4155. * time go backwards.
  4156. *
  4157. * In case we update the frequency for another cpu
  4158. * (which might be in guest context) send an interrupt
  4159. * to kick the cpu out of guest context. Next time
  4160. * guest context is entered kvmclock will be updated,
  4161. * so the guest will not see stale values.
  4162. */
  4163. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  4164. }
  4165. return 0;
  4166. }
  4167. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  4168. .notifier_call = kvmclock_cpufreq_notifier
  4169. };
  4170. static int kvmclock_cpu_notifier(struct notifier_block *nfb,
  4171. unsigned long action, void *hcpu)
  4172. {
  4173. unsigned int cpu = (unsigned long)hcpu;
  4174. switch (action) {
  4175. case CPU_ONLINE:
  4176. case CPU_DOWN_FAILED:
  4177. smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
  4178. break;
  4179. case CPU_DOWN_PREPARE:
  4180. smp_call_function_single(cpu, tsc_bad, NULL, 1);
  4181. break;
  4182. }
  4183. return NOTIFY_OK;
  4184. }
  4185. static struct notifier_block kvmclock_cpu_notifier_block = {
  4186. .notifier_call = kvmclock_cpu_notifier,
  4187. .priority = -INT_MAX
  4188. };
  4189. static void kvm_timer_init(void)
  4190. {
  4191. int cpu;
  4192. max_tsc_khz = tsc_khz;
  4193. register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
  4194. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  4195. #ifdef CONFIG_CPU_FREQ
  4196. struct cpufreq_policy policy;
  4197. memset(&policy, 0, sizeof(policy));
  4198. cpu = get_cpu();
  4199. cpufreq_get_policy(&policy, cpu);
  4200. if (policy.cpuinfo.max_freq)
  4201. max_tsc_khz = policy.cpuinfo.max_freq;
  4202. put_cpu();
  4203. #endif
  4204. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  4205. CPUFREQ_TRANSITION_NOTIFIER);
  4206. }
  4207. pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
  4208. for_each_online_cpu(cpu)
  4209. smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
  4210. }
  4211. static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
  4212. int kvm_is_in_guest(void)
  4213. {
  4214. return __this_cpu_read(current_vcpu) != NULL;
  4215. }
  4216. static int kvm_is_user_mode(void)
  4217. {
  4218. int user_mode = 3;
  4219. if (__this_cpu_read(current_vcpu))
  4220. user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
  4221. return user_mode != 0;
  4222. }
  4223. static unsigned long kvm_get_guest_ip(void)
  4224. {
  4225. unsigned long ip = 0;
  4226. if (__this_cpu_read(current_vcpu))
  4227. ip = kvm_rip_read(__this_cpu_read(current_vcpu));
  4228. return ip;
  4229. }
  4230. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  4231. .is_in_guest = kvm_is_in_guest,
  4232. .is_user_mode = kvm_is_user_mode,
  4233. .get_guest_ip = kvm_get_guest_ip,
  4234. };
  4235. void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
  4236. {
  4237. __this_cpu_write(current_vcpu, vcpu);
  4238. }
  4239. EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
  4240. void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
  4241. {
  4242. __this_cpu_write(current_vcpu, NULL);
  4243. }
  4244. EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
  4245. static void kvm_set_mmio_spte_mask(void)
  4246. {
  4247. u64 mask;
  4248. int maxphyaddr = boot_cpu_data.x86_phys_bits;
  4249. /*
  4250. * Set the reserved bits and the present bit of an paging-structure
  4251. * entry to generate page fault with PFER.RSV = 1.
  4252. */
  4253. mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
  4254. mask |= 1ull;
  4255. #ifdef CONFIG_X86_64
  4256. /*
  4257. * If reserved bit is not supported, clear the present bit to disable
  4258. * mmio page fault.
  4259. */
  4260. if (maxphyaddr == 52)
  4261. mask &= ~1ull;
  4262. #endif
  4263. kvm_mmu_set_mmio_spte_mask(mask);
  4264. }
  4265. #ifdef CONFIG_X86_64
  4266. static void pvclock_gtod_update_fn(struct work_struct *work)
  4267. {
  4268. }
  4269. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  4270. /*
  4271. * Notification about pvclock gtod data update.
  4272. */
  4273. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  4274. void *priv)
  4275. {
  4276. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  4277. struct timekeeper *tk = priv;
  4278. update_pvclock_gtod(tk);
  4279. /* disable master clock if host does not trust, or does not
  4280. * use, TSC clocksource
  4281. */
  4282. if (gtod->clock.vclock_mode != VCLOCK_TSC &&
  4283. atomic_read(&kvm_guest_has_master_clock) != 0)
  4284. queue_work(system_long_wq, &pvclock_gtod_work);
  4285. return 0;
  4286. }
  4287. static struct notifier_block pvclock_gtod_notifier = {
  4288. .notifier_call = pvclock_gtod_notify,
  4289. };
  4290. #endif
  4291. int kvm_arch_init(void *opaque)
  4292. {
  4293. int r;
  4294. struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
  4295. if (kvm_x86_ops) {
  4296. printk(KERN_ERR "kvm: already loaded the other module\n");
  4297. r = -EEXIST;
  4298. goto out;
  4299. }
  4300. if (!ops->cpu_has_kvm_support()) {
  4301. printk(KERN_ERR "kvm: no hardware support\n");
  4302. r = -EOPNOTSUPP;
  4303. goto out;
  4304. }
  4305. if (ops->disabled_by_bios()) {
  4306. printk(KERN_ERR "kvm: disabled by bios\n");
  4307. r = -EOPNOTSUPP;
  4308. goto out;
  4309. }
  4310. r = kvm_mmu_module_init();
  4311. if (r)
  4312. goto out;
  4313. kvm_set_mmio_spte_mask();
  4314. kvm_init_msr_list();
  4315. kvm_x86_ops = ops;
  4316. kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
  4317. PT_DIRTY_MASK, PT64_NX_MASK, 0);
  4318. kvm_timer_init();
  4319. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  4320. if (cpu_has_xsave)
  4321. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  4322. kvm_lapic_init();
  4323. #ifdef CONFIG_X86_64
  4324. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  4325. #endif
  4326. return 0;
  4327. out:
  4328. return r;
  4329. }
  4330. void kvm_arch_exit(void)
  4331. {
  4332. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  4333. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  4334. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  4335. CPUFREQ_TRANSITION_NOTIFIER);
  4336. unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
  4337. #ifdef CONFIG_X86_64
  4338. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  4339. #endif
  4340. kvm_x86_ops = NULL;
  4341. kvm_mmu_module_exit();
  4342. }
  4343. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  4344. {
  4345. ++vcpu->stat.halt_exits;
  4346. if (irqchip_in_kernel(vcpu->kvm)) {
  4347. vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
  4348. return 1;
  4349. } else {
  4350. vcpu->run->exit_reason = KVM_EXIT_HLT;
  4351. return 0;
  4352. }
  4353. }
  4354. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  4355. int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
  4356. {
  4357. u64 param, ingpa, outgpa, ret;
  4358. uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
  4359. bool fast, longmode;
  4360. int cs_db, cs_l;
  4361. /*
  4362. * hypercall generates UD from non zero cpl and real mode
  4363. * per HYPER-V spec
  4364. */
  4365. if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
  4366. kvm_queue_exception(vcpu, UD_VECTOR);
  4367. return 0;
  4368. }
  4369. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  4370. longmode = is_long_mode(vcpu) && cs_l == 1;
  4371. if (!longmode) {
  4372. param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
  4373. (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
  4374. ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
  4375. (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
  4376. outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
  4377. (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
  4378. }
  4379. #ifdef CONFIG_X86_64
  4380. else {
  4381. param = kvm_register_read(vcpu, VCPU_REGS_RCX);
  4382. ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
  4383. outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
  4384. }
  4385. #endif
  4386. code = param & 0xffff;
  4387. fast = (param >> 16) & 0x1;
  4388. rep_cnt = (param >> 32) & 0xfff;
  4389. rep_idx = (param >> 48) & 0xfff;
  4390. trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
  4391. switch (code) {
  4392. case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
  4393. kvm_vcpu_on_spin(vcpu);
  4394. break;
  4395. default:
  4396. res = HV_STATUS_INVALID_HYPERCALL_CODE;
  4397. break;
  4398. }
  4399. ret = res | (((u64)rep_done & 0xfff) << 32);
  4400. if (longmode) {
  4401. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  4402. } else {
  4403. kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
  4404. kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
  4405. }
  4406. return 1;
  4407. }
  4408. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  4409. {
  4410. unsigned long nr, a0, a1, a2, a3, ret;
  4411. int r = 1;
  4412. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  4413. return kvm_hv_hypercall(vcpu);
  4414. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4415. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  4416. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  4417. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  4418. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  4419. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  4420. if (!is_long_mode(vcpu)) {
  4421. nr &= 0xFFFFFFFF;
  4422. a0 &= 0xFFFFFFFF;
  4423. a1 &= 0xFFFFFFFF;
  4424. a2 &= 0xFFFFFFFF;
  4425. a3 &= 0xFFFFFFFF;
  4426. }
  4427. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  4428. ret = -KVM_EPERM;
  4429. goto out;
  4430. }
  4431. switch (nr) {
  4432. case KVM_HC_VAPIC_POLL_IRQ:
  4433. ret = 0;
  4434. break;
  4435. default:
  4436. ret = -KVM_ENOSYS;
  4437. break;
  4438. }
  4439. out:
  4440. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  4441. ++vcpu->stat.hypercalls;
  4442. return r;
  4443. }
  4444. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  4445. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  4446. {
  4447. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4448. char instruction[3];
  4449. unsigned long rip = kvm_rip_read(vcpu);
  4450. /*
  4451. * Blow out the MMU to ensure that no other VCPU has an active mapping
  4452. * to ensure that the updated hypercall appears atomically across all
  4453. * VCPUs.
  4454. */
  4455. kvm_mmu_zap_all(vcpu->kvm);
  4456. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  4457. return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
  4458. }
  4459. /*
  4460. * Check if userspace requested an interrupt window, and that the
  4461. * interrupt window is open.
  4462. *
  4463. * No need to exit to userspace if we already have an interrupt queued.
  4464. */
  4465. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  4466. {
  4467. return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
  4468. vcpu->run->request_interrupt_window &&
  4469. kvm_arch_interrupt_allowed(vcpu));
  4470. }
  4471. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  4472. {
  4473. struct kvm_run *kvm_run = vcpu->run;
  4474. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  4475. kvm_run->cr8 = kvm_get_cr8(vcpu);
  4476. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  4477. if (irqchip_in_kernel(vcpu->kvm))
  4478. kvm_run->ready_for_interrupt_injection = 1;
  4479. else
  4480. kvm_run->ready_for_interrupt_injection =
  4481. kvm_arch_interrupt_allowed(vcpu) &&
  4482. !kvm_cpu_has_interrupt(vcpu) &&
  4483. !kvm_event_needs_reinjection(vcpu);
  4484. }
  4485. static int vapic_enter(struct kvm_vcpu *vcpu)
  4486. {
  4487. struct kvm_lapic *apic = vcpu->arch.apic;
  4488. struct page *page;
  4489. if (!apic || !apic->vapic_addr)
  4490. return 0;
  4491. page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
  4492. if (is_error_page(page))
  4493. return -EFAULT;
  4494. vcpu->arch.apic->vapic_page = page;
  4495. return 0;
  4496. }
  4497. static void vapic_exit(struct kvm_vcpu *vcpu)
  4498. {
  4499. struct kvm_lapic *apic = vcpu->arch.apic;
  4500. int idx;
  4501. if (!apic || !apic->vapic_addr)
  4502. return;
  4503. idx = srcu_read_lock(&vcpu->kvm->srcu);
  4504. kvm_release_page_dirty(apic->vapic_page);
  4505. mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
  4506. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4507. }
  4508. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  4509. {
  4510. int max_irr, tpr;
  4511. if (!kvm_x86_ops->update_cr8_intercept)
  4512. return;
  4513. if (!vcpu->arch.apic)
  4514. return;
  4515. if (!vcpu->arch.apic->vapic_addr)
  4516. max_irr = kvm_lapic_find_highest_irr(vcpu);
  4517. else
  4518. max_irr = -1;
  4519. if (max_irr != -1)
  4520. max_irr >>= 4;
  4521. tpr = kvm_lapic_get_cr8(vcpu);
  4522. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  4523. }
  4524. static void inject_pending_event(struct kvm_vcpu *vcpu)
  4525. {
  4526. /* try to reinject previous events if any */
  4527. if (vcpu->arch.exception.pending) {
  4528. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  4529. vcpu->arch.exception.has_error_code,
  4530. vcpu->arch.exception.error_code);
  4531. kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
  4532. vcpu->arch.exception.has_error_code,
  4533. vcpu->arch.exception.error_code,
  4534. vcpu->arch.exception.reinject);
  4535. return;
  4536. }
  4537. if (vcpu->arch.nmi_injected) {
  4538. kvm_x86_ops->set_nmi(vcpu);
  4539. return;
  4540. }
  4541. if (vcpu->arch.interrupt.pending) {
  4542. kvm_x86_ops->set_irq(vcpu);
  4543. return;
  4544. }
  4545. /* try to inject new event if pending */
  4546. if (vcpu->arch.nmi_pending) {
  4547. if (kvm_x86_ops->nmi_allowed(vcpu)) {
  4548. --vcpu->arch.nmi_pending;
  4549. vcpu->arch.nmi_injected = true;
  4550. kvm_x86_ops->set_nmi(vcpu);
  4551. }
  4552. } else if (kvm_cpu_has_interrupt(vcpu)) {
  4553. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  4554. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  4555. false);
  4556. kvm_x86_ops->set_irq(vcpu);
  4557. }
  4558. }
  4559. }
  4560. static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  4561. {
  4562. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  4563. !vcpu->guest_xcr0_loaded) {
  4564. /* kvm_set_xcr() also depends on this */
  4565. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  4566. vcpu->guest_xcr0_loaded = 1;
  4567. }
  4568. }
  4569. static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  4570. {
  4571. if (vcpu->guest_xcr0_loaded) {
  4572. if (vcpu->arch.xcr0 != host_xcr0)
  4573. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  4574. vcpu->guest_xcr0_loaded = 0;
  4575. }
  4576. }
  4577. static void process_nmi(struct kvm_vcpu *vcpu)
  4578. {
  4579. unsigned limit = 2;
  4580. /*
  4581. * x86 is limited to one NMI running, and one NMI pending after it.
  4582. * If an NMI is already in progress, limit further NMIs to just one.
  4583. * Otherwise, allow two (and we'll inject the first one immediately).
  4584. */
  4585. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  4586. limit = 1;
  4587. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  4588. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  4589. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4590. }
  4591. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  4592. {
  4593. int r;
  4594. bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
  4595. vcpu->run->request_interrupt_window;
  4596. bool req_immediate_exit = 0;
  4597. if (vcpu->requests) {
  4598. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  4599. kvm_mmu_unload(vcpu);
  4600. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  4601. __kvm_migrate_timers(vcpu);
  4602. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  4603. r = kvm_guest_time_update(vcpu);
  4604. if (unlikely(r))
  4605. goto out;
  4606. }
  4607. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  4608. kvm_mmu_sync_roots(vcpu);
  4609. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  4610. kvm_x86_ops->tlb_flush(vcpu);
  4611. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  4612. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  4613. r = 0;
  4614. goto out;
  4615. }
  4616. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  4617. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  4618. r = 0;
  4619. goto out;
  4620. }
  4621. if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
  4622. vcpu->fpu_active = 0;
  4623. kvm_x86_ops->fpu_deactivate(vcpu);
  4624. }
  4625. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  4626. /* Page is swapped out. Do synthetic halt */
  4627. vcpu->arch.apf.halted = true;
  4628. r = 1;
  4629. goto out;
  4630. }
  4631. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  4632. record_steal_time(vcpu);
  4633. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  4634. process_nmi(vcpu);
  4635. req_immediate_exit =
  4636. kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
  4637. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  4638. kvm_handle_pmu_event(vcpu);
  4639. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  4640. kvm_deliver_pmi(vcpu);
  4641. }
  4642. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  4643. inject_pending_event(vcpu);
  4644. /* enable NMI/IRQ window open exits if needed */
  4645. if (vcpu->arch.nmi_pending)
  4646. kvm_x86_ops->enable_nmi_window(vcpu);
  4647. else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
  4648. kvm_x86_ops->enable_irq_window(vcpu);
  4649. if (kvm_lapic_enabled(vcpu)) {
  4650. update_cr8_intercept(vcpu);
  4651. kvm_lapic_sync_to_vapic(vcpu);
  4652. }
  4653. }
  4654. r = kvm_mmu_reload(vcpu);
  4655. if (unlikely(r)) {
  4656. goto cancel_injection;
  4657. }
  4658. preempt_disable();
  4659. kvm_x86_ops->prepare_guest_switch(vcpu);
  4660. if (vcpu->fpu_active)
  4661. kvm_load_guest_fpu(vcpu);
  4662. kvm_load_guest_xcr0(vcpu);
  4663. vcpu->mode = IN_GUEST_MODE;
  4664. /* We should set ->mode before check ->requests,
  4665. * see the comment in make_all_cpus_request.
  4666. */
  4667. smp_mb();
  4668. local_irq_disable();
  4669. if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
  4670. || need_resched() || signal_pending(current)) {
  4671. vcpu->mode = OUTSIDE_GUEST_MODE;
  4672. smp_wmb();
  4673. local_irq_enable();
  4674. preempt_enable();
  4675. r = 1;
  4676. goto cancel_injection;
  4677. }
  4678. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  4679. if (req_immediate_exit)
  4680. smp_send_reschedule(vcpu->cpu);
  4681. kvm_guest_enter();
  4682. if (unlikely(vcpu->arch.switch_db_regs)) {
  4683. set_debugreg(0, 7);
  4684. set_debugreg(vcpu->arch.eff_db[0], 0);
  4685. set_debugreg(vcpu->arch.eff_db[1], 1);
  4686. set_debugreg(vcpu->arch.eff_db[2], 2);
  4687. set_debugreg(vcpu->arch.eff_db[3], 3);
  4688. }
  4689. trace_kvm_entry(vcpu->vcpu_id);
  4690. kvm_x86_ops->run(vcpu);
  4691. /*
  4692. * If the guest has used debug registers, at least dr7
  4693. * will be disabled while returning to the host.
  4694. * If we don't have active breakpoints in the host, we don't
  4695. * care about the messed up debug address registers. But if
  4696. * we have some of them active, restore the old state.
  4697. */
  4698. if (hw_breakpoint_active())
  4699. hw_breakpoint_restore();
  4700. vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
  4701. native_read_tsc());
  4702. vcpu->mode = OUTSIDE_GUEST_MODE;
  4703. smp_wmb();
  4704. local_irq_enable();
  4705. ++vcpu->stat.exits;
  4706. /*
  4707. * We must have an instruction between local_irq_enable() and
  4708. * kvm_guest_exit(), so the timer interrupt isn't delayed by
  4709. * the interrupt shadow. The stat.exits increment will do nicely.
  4710. * But we need to prevent reordering, hence this barrier():
  4711. */
  4712. barrier();
  4713. kvm_guest_exit();
  4714. preempt_enable();
  4715. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  4716. /*
  4717. * Profile KVM exit RIPs:
  4718. */
  4719. if (unlikely(prof_on == KVM_PROFILING)) {
  4720. unsigned long rip = kvm_rip_read(vcpu);
  4721. profile_hit(KVM_PROFILING, (void *)rip);
  4722. }
  4723. if (unlikely(vcpu->arch.tsc_always_catchup))
  4724. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  4725. if (vcpu->arch.apic_attention)
  4726. kvm_lapic_sync_from_vapic(vcpu);
  4727. r = kvm_x86_ops->handle_exit(vcpu);
  4728. return r;
  4729. cancel_injection:
  4730. kvm_x86_ops->cancel_injection(vcpu);
  4731. if (unlikely(vcpu->arch.apic_attention))
  4732. kvm_lapic_sync_from_vapic(vcpu);
  4733. out:
  4734. return r;
  4735. }
  4736. static int __vcpu_run(struct kvm_vcpu *vcpu)
  4737. {
  4738. int r;
  4739. struct kvm *kvm = vcpu->kvm;
  4740. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
  4741. pr_debug("vcpu %d received sipi with vector # %x\n",
  4742. vcpu->vcpu_id, vcpu->arch.sipi_vector);
  4743. kvm_lapic_reset(vcpu);
  4744. r = kvm_vcpu_reset(vcpu);
  4745. if (r)
  4746. return r;
  4747. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  4748. }
  4749. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  4750. r = vapic_enter(vcpu);
  4751. if (r) {
  4752. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  4753. return r;
  4754. }
  4755. r = 1;
  4756. while (r > 0) {
  4757. if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  4758. !vcpu->arch.apf.halted)
  4759. r = vcpu_enter_guest(vcpu);
  4760. else {
  4761. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  4762. kvm_vcpu_block(vcpu);
  4763. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  4764. if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
  4765. {
  4766. switch(vcpu->arch.mp_state) {
  4767. case KVM_MP_STATE_HALTED:
  4768. vcpu->arch.mp_state =
  4769. KVM_MP_STATE_RUNNABLE;
  4770. case KVM_MP_STATE_RUNNABLE:
  4771. vcpu->arch.apf.halted = false;
  4772. break;
  4773. case KVM_MP_STATE_SIPI_RECEIVED:
  4774. default:
  4775. r = -EINTR;
  4776. break;
  4777. }
  4778. }
  4779. }
  4780. if (r <= 0)
  4781. break;
  4782. clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
  4783. if (kvm_cpu_has_pending_timer(vcpu))
  4784. kvm_inject_pending_timer_irqs(vcpu);
  4785. if (dm_request_for_irq_injection(vcpu)) {
  4786. r = -EINTR;
  4787. vcpu->run->exit_reason = KVM_EXIT_INTR;
  4788. ++vcpu->stat.request_irq_exits;
  4789. }
  4790. kvm_check_async_pf_completion(vcpu);
  4791. if (signal_pending(current)) {
  4792. r = -EINTR;
  4793. vcpu->run->exit_reason = KVM_EXIT_INTR;
  4794. ++vcpu->stat.signal_exits;
  4795. }
  4796. if (need_resched()) {
  4797. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  4798. kvm_resched(vcpu);
  4799. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  4800. }
  4801. }
  4802. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  4803. vapic_exit(vcpu);
  4804. return r;
  4805. }
  4806. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  4807. {
  4808. int r;
  4809. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  4810. r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  4811. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  4812. if (r != EMULATE_DONE)
  4813. return 0;
  4814. return 1;
  4815. }
  4816. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  4817. {
  4818. BUG_ON(!vcpu->arch.pio.count);
  4819. return complete_emulated_io(vcpu);
  4820. }
  4821. /*
  4822. * Implements the following, as a state machine:
  4823. *
  4824. * read:
  4825. * for each fragment
  4826. * write gpa, len
  4827. * exit
  4828. * copy data
  4829. * execute insn
  4830. *
  4831. * write:
  4832. * for each fragment
  4833. * write gpa, len
  4834. * copy data
  4835. * exit
  4836. */
  4837. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  4838. {
  4839. struct kvm_run *run = vcpu->run;
  4840. struct kvm_mmio_fragment *frag;
  4841. BUG_ON(!vcpu->mmio_needed);
  4842. /* Complete previous fragment */
  4843. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment++];
  4844. if (!vcpu->mmio_is_write)
  4845. memcpy(frag->data, run->mmio.data, frag->len);
  4846. if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
  4847. vcpu->mmio_needed = 0;
  4848. if (vcpu->mmio_is_write)
  4849. return 1;
  4850. vcpu->mmio_read_completed = 1;
  4851. return complete_emulated_io(vcpu);
  4852. }
  4853. /* Initiate next fragment */
  4854. ++frag;
  4855. run->exit_reason = KVM_EXIT_MMIO;
  4856. run->mmio.phys_addr = frag->gpa;
  4857. if (vcpu->mmio_is_write)
  4858. memcpy(run->mmio.data, frag->data, frag->len);
  4859. run->mmio.len = frag->len;
  4860. run->mmio.is_write = vcpu->mmio_is_write;
  4861. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  4862. return 0;
  4863. }
  4864. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  4865. {
  4866. int r;
  4867. sigset_t sigsaved;
  4868. if (!tsk_used_math(current) && init_fpu(current))
  4869. return -ENOMEM;
  4870. if (vcpu->sigset_active)
  4871. sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
  4872. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  4873. kvm_vcpu_block(vcpu);
  4874. clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
  4875. r = -EAGAIN;
  4876. goto out;
  4877. }
  4878. /* re-sync apic's tpr */
  4879. if (!irqchip_in_kernel(vcpu->kvm)) {
  4880. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  4881. r = -EINVAL;
  4882. goto out;
  4883. }
  4884. }
  4885. if (unlikely(vcpu->arch.complete_userspace_io)) {
  4886. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  4887. vcpu->arch.complete_userspace_io = NULL;
  4888. r = cui(vcpu);
  4889. if (r <= 0)
  4890. goto out;
  4891. } else
  4892. WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
  4893. r = __vcpu_run(vcpu);
  4894. out:
  4895. post_kvm_run_save(vcpu);
  4896. if (vcpu->sigset_active)
  4897. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  4898. return r;
  4899. }
  4900. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  4901. {
  4902. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  4903. /*
  4904. * We are here if userspace calls get_regs() in the middle of
  4905. * instruction emulation. Registers state needs to be copied
  4906. * back from emulation context to vcpu. Userspace shouldn't do
  4907. * that usually, but some bad designed PV devices (vmware
  4908. * backdoor interface) need this to work
  4909. */
  4910. emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
  4911. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  4912. }
  4913. regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4914. regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  4915. regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  4916. regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  4917. regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  4918. regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  4919. regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  4920. regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
  4921. #ifdef CONFIG_X86_64
  4922. regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  4923. regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  4924. regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  4925. regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  4926. regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  4927. regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  4928. regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  4929. regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
  4930. #endif
  4931. regs->rip = kvm_rip_read(vcpu);
  4932. regs->rflags = kvm_get_rflags(vcpu);
  4933. return 0;
  4934. }
  4935. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  4936. {
  4937. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  4938. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  4939. kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  4940. kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  4941. kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  4942. kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  4943. kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  4944. kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  4945. kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  4946. kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
  4947. #ifdef CONFIG_X86_64
  4948. kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  4949. kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  4950. kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  4951. kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  4952. kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  4953. kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  4954. kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  4955. kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
  4956. #endif
  4957. kvm_rip_write(vcpu, regs->rip);
  4958. kvm_set_rflags(vcpu, regs->rflags);
  4959. vcpu->arch.exception.pending = false;
  4960. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4961. return 0;
  4962. }
  4963. void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  4964. {
  4965. struct kvm_segment cs;
  4966. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  4967. *db = cs.db;
  4968. *l = cs.l;
  4969. }
  4970. EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  4971. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  4972. struct kvm_sregs *sregs)
  4973. {
  4974. struct desc_ptr dt;
  4975. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  4976. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  4977. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  4978. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  4979. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  4980. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  4981. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  4982. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  4983. kvm_x86_ops->get_idt(vcpu, &dt);
  4984. sregs->idt.limit = dt.size;
  4985. sregs->idt.base = dt.address;
  4986. kvm_x86_ops->get_gdt(vcpu, &dt);
  4987. sregs->gdt.limit = dt.size;
  4988. sregs->gdt.base = dt.address;
  4989. sregs->cr0 = kvm_read_cr0(vcpu);
  4990. sregs->cr2 = vcpu->arch.cr2;
  4991. sregs->cr3 = kvm_read_cr3(vcpu);
  4992. sregs->cr4 = kvm_read_cr4(vcpu);
  4993. sregs->cr8 = kvm_get_cr8(vcpu);
  4994. sregs->efer = vcpu->arch.efer;
  4995. sregs->apic_base = kvm_get_apic_base(vcpu);
  4996. memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
  4997. if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
  4998. set_bit(vcpu->arch.interrupt.nr,
  4999. (unsigned long *)sregs->interrupt_bitmap);
  5000. return 0;
  5001. }
  5002. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  5003. struct kvm_mp_state *mp_state)
  5004. {
  5005. mp_state->mp_state = vcpu->arch.mp_state;
  5006. return 0;
  5007. }
  5008. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  5009. struct kvm_mp_state *mp_state)
  5010. {
  5011. vcpu->arch.mp_state = mp_state->mp_state;
  5012. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5013. return 0;
  5014. }
  5015. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  5016. int reason, bool has_error_code, u32 error_code)
  5017. {
  5018. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5019. int ret;
  5020. init_emulate_ctxt(vcpu);
  5021. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  5022. has_error_code, error_code);
  5023. if (ret)
  5024. return EMULATE_FAIL;
  5025. kvm_rip_write(vcpu, ctxt->eip);
  5026. kvm_set_rflags(vcpu, ctxt->eflags);
  5027. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5028. return EMULATE_DONE;
  5029. }
  5030. EXPORT_SYMBOL_GPL(kvm_task_switch);
  5031. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  5032. struct kvm_sregs *sregs)
  5033. {
  5034. int mmu_reset_needed = 0;
  5035. int pending_vec, max_bits, idx;
  5036. struct desc_ptr dt;
  5037. dt.size = sregs->idt.limit;
  5038. dt.address = sregs->idt.base;
  5039. kvm_x86_ops->set_idt(vcpu, &dt);
  5040. dt.size = sregs->gdt.limit;
  5041. dt.address = sregs->gdt.base;
  5042. kvm_x86_ops->set_gdt(vcpu, &dt);
  5043. vcpu->arch.cr2 = sregs->cr2;
  5044. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  5045. vcpu->arch.cr3 = sregs->cr3;
  5046. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  5047. kvm_set_cr8(vcpu, sregs->cr8);
  5048. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  5049. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  5050. kvm_set_apic_base(vcpu, sregs->apic_base);
  5051. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  5052. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  5053. vcpu->arch.cr0 = sregs->cr0;
  5054. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  5055. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  5056. if (sregs->cr4 & X86_CR4_OSXSAVE)
  5057. kvm_update_cpuid(vcpu);
  5058. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5059. if (!is_long_mode(vcpu) && is_pae(vcpu)) {
  5060. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  5061. mmu_reset_needed = 1;
  5062. }
  5063. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5064. if (mmu_reset_needed)
  5065. kvm_mmu_reset_context(vcpu);
  5066. max_bits = KVM_NR_INTERRUPTS;
  5067. pending_vec = find_first_bit(
  5068. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  5069. if (pending_vec < max_bits) {
  5070. kvm_queue_interrupt(vcpu, pending_vec, false);
  5071. pr_debug("Set back pending irq %d\n", pending_vec);
  5072. }
  5073. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  5074. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  5075. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  5076. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  5077. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  5078. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  5079. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  5080. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  5081. update_cr8_intercept(vcpu);
  5082. /* Older userspace won't unhalt the vcpu on reset. */
  5083. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  5084. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  5085. !is_protmode(vcpu))
  5086. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  5087. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5088. return 0;
  5089. }
  5090. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  5091. struct kvm_guest_debug *dbg)
  5092. {
  5093. unsigned long rflags;
  5094. int i, r;
  5095. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  5096. r = -EBUSY;
  5097. if (vcpu->arch.exception.pending)
  5098. goto out;
  5099. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  5100. kvm_queue_exception(vcpu, DB_VECTOR);
  5101. else
  5102. kvm_queue_exception(vcpu, BP_VECTOR);
  5103. }
  5104. /*
  5105. * Read rflags as long as potentially injected trace flags are still
  5106. * filtered out.
  5107. */
  5108. rflags = kvm_get_rflags(vcpu);
  5109. vcpu->guest_debug = dbg->control;
  5110. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  5111. vcpu->guest_debug = 0;
  5112. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  5113. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  5114. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  5115. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  5116. } else {
  5117. for (i = 0; i < KVM_NR_DB_REGS; i++)
  5118. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  5119. }
  5120. kvm_update_dr7(vcpu);
  5121. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  5122. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  5123. get_segment_base(vcpu, VCPU_SREG_CS);
  5124. /*
  5125. * Trigger an rflags update that will inject or remove the trace
  5126. * flags.
  5127. */
  5128. kvm_set_rflags(vcpu, rflags);
  5129. kvm_x86_ops->update_db_bp_intercept(vcpu);
  5130. r = 0;
  5131. out:
  5132. return r;
  5133. }
  5134. /*
  5135. * Translate a guest virtual address to a guest physical address.
  5136. */
  5137. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  5138. struct kvm_translation *tr)
  5139. {
  5140. unsigned long vaddr = tr->linear_address;
  5141. gpa_t gpa;
  5142. int idx;
  5143. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5144. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  5145. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5146. tr->physical_address = gpa;
  5147. tr->valid = gpa != UNMAPPED_GVA;
  5148. tr->writeable = 1;
  5149. tr->usermode = 0;
  5150. return 0;
  5151. }
  5152. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  5153. {
  5154. struct i387_fxsave_struct *fxsave =
  5155. &vcpu->arch.guest_fpu.state->fxsave;
  5156. memcpy(fpu->fpr, fxsave->st_space, 128);
  5157. fpu->fcw = fxsave->cwd;
  5158. fpu->fsw = fxsave->swd;
  5159. fpu->ftwx = fxsave->twd;
  5160. fpu->last_opcode = fxsave->fop;
  5161. fpu->last_ip = fxsave->rip;
  5162. fpu->last_dp = fxsave->rdp;
  5163. memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
  5164. return 0;
  5165. }
  5166. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  5167. {
  5168. struct i387_fxsave_struct *fxsave =
  5169. &vcpu->arch.guest_fpu.state->fxsave;
  5170. memcpy(fxsave->st_space, fpu->fpr, 128);
  5171. fxsave->cwd = fpu->fcw;
  5172. fxsave->swd = fpu->fsw;
  5173. fxsave->twd = fpu->ftwx;
  5174. fxsave->fop = fpu->last_opcode;
  5175. fxsave->rip = fpu->last_ip;
  5176. fxsave->rdp = fpu->last_dp;
  5177. memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
  5178. return 0;
  5179. }
  5180. int fx_init(struct kvm_vcpu *vcpu)
  5181. {
  5182. int err;
  5183. err = fpu_alloc(&vcpu->arch.guest_fpu);
  5184. if (err)
  5185. return err;
  5186. fpu_finit(&vcpu->arch.guest_fpu);
  5187. /*
  5188. * Ensure guest xcr0 is valid for loading
  5189. */
  5190. vcpu->arch.xcr0 = XSTATE_FP;
  5191. vcpu->arch.cr0 |= X86_CR0_ET;
  5192. return 0;
  5193. }
  5194. EXPORT_SYMBOL_GPL(fx_init);
  5195. static void fx_free(struct kvm_vcpu *vcpu)
  5196. {
  5197. fpu_free(&vcpu->arch.guest_fpu);
  5198. }
  5199. void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  5200. {
  5201. if (vcpu->guest_fpu_loaded)
  5202. return;
  5203. /*
  5204. * Restore all possible states in the guest,
  5205. * and assume host would use all available bits.
  5206. * Guest xcr0 would be loaded later.
  5207. */
  5208. kvm_put_guest_xcr0(vcpu);
  5209. vcpu->guest_fpu_loaded = 1;
  5210. __kernel_fpu_begin();
  5211. fpu_restore_checking(&vcpu->arch.guest_fpu);
  5212. trace_kvm_fpu(1);
  5213. }
  5214. void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  5215. {
  5216. kvm_put_guest_xcr0(vcpu);
  5217. if (!vcpu->guest_fpu_loaded)
  5218. return;
  5219. vcpu->guest_fpu_loaded = 0;
  5220. fpu_save_init(&vcpu->arch.guest_fpu);
  5221. __kernel_fpu_end();
  5222. ++vcpu->stat.fpu_reload;
  5223. kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
  5224. trace_kvm_fpu(0);
  5225. }
  5226. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  5227. {
  5228. kvmclock_reset(vcpu);
  5229. free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
  5230. fx_free(vcpu);
  5231. kvm_x86_ops->vcpu_free(vcpu);
  5232. }
  5233. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  5234. unsigned int id)
  5235. {
  5236. if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  5237. printk_once(KERN_WARNING
  5238. "kvm: SMP vm created on host with unstable TSC; "
  5239. "guest TSC will not be reliable\n");
  5240. return kvm_x86_ops->vcpu_create(kvm, id);
  5241. }
  5242. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  5243. {
  5244. int r;
  5245. vcpu->arch.mtrr_state.have_fixed = 1;
  5246. r = vcpu_load(vcpu);
  5247. if (r)
  5248. return r;
  5249. r = kvm_vcpu_reset(vcpu);
  5250. if (r == 0)
  5251. r = kvm_mmu_setup(vcpu);
  5252. vcpu_put(vcpu);
  5253. return r;
  5254. }
  5255. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  5256. {
  5257. int r;
  5258. vcpu->arch.apf.msr_val = 0;
  5259. r = vcpu_load(vcpu);
  5260. BUG_ON(r);
  5261. kvm_mmu_unload(vcpu);
  5262. vcpu_put(vcpu);
  5263. fx_free(vcpu);
  5264. kvm_x86_ops->vcpu_free(vcpu);
  5265. }
  5266. static int kvm_vcpu_reset(struct kvm_vcpu *vcpu)
  5267. {
  5268. atomic_set(&vcpu->arch.nmi_queued, 0);
  5269. vcpu->arch.nmi_pending = 0;
  5270. vcpu->arch.nmi_injected = false;
  5271. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  5272. vcpu->arch.dr6 = DR6_FIXED_1;
  5273. vcpu->arch.dr7 = DR7_FIXED_1;
  5274. kvm_update_dr7(vcpu);
  5275. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5276. vcpu->arch.apf.msr_val = 0;
  5277. vcpu->arch.st.msr_val = 0;
  5278. kvmclock_reset(vcpu);
  5279. kvm_clear_async_pf_completion_queue(vcpu);
  5280. kvm_async_pf_hash_reset(vcpu);
  5281. vcpu->arch.apf.halted = false;
  5282. kvm_pmu_reset(vcpu);
  5283. return kvm_x86_ops->vcpu_reset(vcpu);
  5284. }
  5285. int kvm_arch_hardware_enable(void *garbage)
  5286. {
  5287. struct kvm *kvm;
  5288. struct kvm_vcpu *vcpu;
  5289. int i;
  5290. int ret;
  5291. u64 local_tsc;
  5292. u64 max_tsc = 0;
  5293. bool stable, backwards_tsc = false;
  5294. kvm_shared_msr_cpu_online();
  5295. ret = kvm_x86_ops->hardware_enable(garbage);
  5296. if (ret != 0)
  5297. return ret;
  5298. local_tsc = native_read_tsc();
  5299. stable = !check_tsc_unstable();
  5300. list_for_each_entry(kvm, &vm_list, vm_list) {
  5301. kvm_for_each_vcpu(i, vcpu, kvm) {
  5302. if (!stable && vcpu->cpu == smp_processor_id())
  5303. set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
  5304. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  5305. backwards_tsc = true;
  5306. if (vcpu->arch.last_host_tsc > max_tsc)
  5307. max_tsc = vcpu->arch.last_host_tsc;
  5308. }
  5309. }
  5310. }
  5311. /*
  5312. * Sometimes, even reliable TSCs go backwards. This happens on
  5313. * platforms that reset TSC during suspend or hibernate actions, but
  5314. * maintain synchronization. We must compensate. Fortunately, we can
  5315. * detect that condition here, which happens early in CPU bringup,
  5316. * before any KVM threads can be running. Unfortunately, we can't
  5317. * bring the TSCs fully up to date with real time, as we aren't yet far
  5318. * enough into CPU bringup that we know how much real time has actually
  5319. * elapsed; our helper function, get_kernel_ns() will be using boot
  5320. * variables that haven't been updated yet.
  5321. *
  5322. * So we simply find the maximum observed TSC above, then record the
  5323. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  5324. * the adjustment will be applied. Note that we accumulate
  5325. * adjustments, in case multiple suspend cycles happen before some VCPU
  5326. * gets a chance to run again. In the event that no KVM threads get a
  5327. * chance to run, we will miss the entire elapsed period, as we'll have
  5328. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  5329. * loose cycle time. This isn't too big a deal, since the loss will be
  5330. * uniform across all VCPUs (not to mention the scenario is extremely
  5331. * unlikely). It is possible that a second hibernate recovery happens
  5332. * much faster than a first, causing the observed TSC here to be
  5333. * smaller; this would require additional padding adjustment, which is
  5334. * why we set last_host_tsc to the local tsc observed here.
  5335. *
  5336. * N.B. - this code below runs only on platforms with reliable TSC,
  5337. * as that is the only way backwards_tsc is set above. Also note
  5338. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  5339. * have the same delta_cyc adjustment applied if backwards_tsc
  5340. * is detected. Note further, this adjustment is only done once,
  5341. * as we reset last_host_tsc on all VCPUs to stop this from being
  5342. * called multiple times (one for each physical CPU bringup).
  5343. *
  5344. * Platforms with unreliable TSCs don't have to deal with this, they
  5345. * will be compensated by the logic in vcpu_load, which sets the TSC to
  5346. * catchup mode. This will catchup all VCPUs to real time, but cannot
  5347. * guarantee that they stay in perfect synchronization.
  5348. */
  5349. if (backwards_tsc) {
  5350. u64 delta_cyc = max_tsc - local_tsc;
  5351. list_for_each_entry(kvm, &vm_list, vm_list) {
  5352. kvm_for_each_vcpu(i, vcpu, kvm) {
  5353. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  5354. vcpu->arch.last_host_tsc = local_tsc;
  5355. }
  5356. /*
  5357. * We have to disable TSC offset matching.. if you were
  5358. * booting a VM while issuing an S4 host suspend....
  5359. * you may have some problem. Solving this issue is
  5360. * left as an exercise to the reader.
  5361. */
  5362. kvm->arch.last_tsc_nsec = 0;
  5363. kvm->arch.last_tsc_write = 0;
  5364. }
  5365. }
  5366. return 0;
  5367. }
  5368. void kvm_arch_hardware_disable(void *garbage)
  5369. {
  5370. kvm_x86_ops->hardware_disable(garbage);
  5371. drop_user_return_notifiers(garbage);
  5372. }
  5373. int kvm_arch_hardware_setup(void)
  5374. {
  5375. return kvm_x86_ops->hardware_setup();
  5376. }
  5377. void kvm_arch_hardware_unsetup(void)
  5378. {
  5379. kvm_x86_ops->hardware_unsetup();
  5380. }
  5381. void kvm_arch_check_processor_compat(void *rtn)
  5382. {
  5383. kvm_x86_ops->check_processor_compatibility(rtn);
  5384. }
  5385. bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
  5386. {
  5387. return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
  5388. }
  5389. struct static_key kvm_no_apic_vcpu __read_mostly;
  5390. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  5391. {
  5392. struct page *page;
  5393. struct kvm *kvm;
  5394. int r;
  5395. BUG_ON(vcpu->kvm == NULL);
  5396. kvm = vcpu->kvm;
  5397. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  5398. if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
  5399. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  5400. else
  5401. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  5402. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  5403. if (!page) {
  5404. r = -ENOMEM;
  5405. goto fail;
  5406. }
  5407. vcpu->arch.pio_data = page_address(page);
  5408. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  5409. r = kvm_mmu_create(vcpu);
  5410. if (r < 0)
  5411. goto fail_free_pio_data;
  5412. if (irqchip_in_kernel(kvm)) {
  5413. r = kvm_create_lapic(vcpu);
  5414. if (r < 0)
  5415. goto fail_mmu_destroy;
  5416. } else
  5417. static_key_slow_inc(&kvm_no_apic_vcpu);
  5418. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  5419. GFP_KERNEL);
  5420. if (!vcpu->arch.mce_banks) {
  5421. r = -ENOMEM;
  5422. goto fail_free_lapic;
  5423. }
  5424. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  5425. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
  5426. goto fail_free_mce_banks;
  5427. kvm_async_pf_hash_reset(vcpu);
  5428. kvm_pmu_init(vcpu);
  5429. return 0;
  5430. fail_free_mce_banks:
  5431. kfree(vcpu->arch.mce_banks);
  5432. fail_free_lapic:
  5433. kvm_free_lapic(vcpu);
  5434. fail_mmu_destroy:
  5435. kvm_mmu_destroy(vcpu);
  5436. fail_free_pio_data:
  5437. free_page((unsigned long)vcpu->arch.pio_data);
  5438. fail:
  5439. return r;
  5440. }
  5441. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  5442. {
  5443. int idx;
  5444. kvm_pmu_destroy(vcpu);
  5445. kfree(vcpu->arch.mce_banks);
  5446. kvm_free_lapic(vcpu);
  5447. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5448. kvm_mmu_destroy(vcpu);
  5449. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5450. free_page((unsigned long)vcpu->arch.pio_data);
  5451. if (!irqchip_in_kernel(vcpu->kvm))
  5452. static_key_slow_dec(&kvm_no_apic_vcpu);
  5453. }
  5454. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  5455. {
  5456. if (type)
  5457. return -EINVAL;
  5458. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  5459. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  5460. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  5461. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  5462. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  5463. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  5464. &kvm->arch.irq_sources_bitmap);
  5465. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  5466. mutex_init(&kvm->arch.apic_map_lock);
  5467. return 0;
  5468. }
  5469. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  5470. {
  5471. int r;
  5472. r = vcpu_load(vcpu);
  5473. BUG_ON(r);
  5474. kvm_mmu_unload(vcpu);
  5475. vcpu_put(vcpu);
  5476. }
  5477. static void kvm_free_vcpus(struct kvm *kvm)
  5478. {
  5479. unsigned int i;
  5480. struct kvm_vcpu *vcpu;
  5481. /*
  5482. * Unpin any mmu pages first.
  5483. */
  5484. kvm_for_each_vcpu(i, vcpu, kvm) {
  5485. kvm_clear_async_pf_completion_queue(vcpu);
  5486. kvm_unload_vcpu_mmu(vcpu);
  5487. }
  5488. kvm_for_each_vcpu(i, vcpu, kvm)
  5489. kvm_arch_vcpu_free(vcpu);
  5490. mutex_lock(&kvm->lock);
  5491. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  5492. kvm->vcpus[i] = NULL;
  5493. atomic_set(&kvm->online_vcpus, 0);
  5494. mutex_unlock(&kvm->lock);
  5495. }
  5496. void kvm_arch_sync_events(struct kvm *kvm)
  5497. {
  5498. kvm_free_all_assigned_devices(kvm);
  5499. kvm_free_pit(kvm);
  5500. }
  5501. void kvm_arch_destroy_vm(struct kvm *kvm)
  5502. {
  5503. kvm_iommu_unmap_guest(kvm);
  5504. kfree(kvm->arch.vpic);
  5505. kfree(kvm->arch.vioapic);
  5506. kvm_free_vcpus(kvm);
  5507. if (kvm->arch.apic_access_page)
  5508. put_page(kvm->arch.apic_access_page);
  5509. if (kvm->arch.ept_identity_pagetable)
  5510. put_page(kvm->arch.ept_identity_pagetable);
  5511. kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  5512. }
  5513. void kvm_arch_free_memslot(struct kvm_memory_slot *free,
  5514. struct kvm_memory_slot *dont)
  5515. {
  5516. int i;
  5517. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5518. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  5519. kvm_kvfree(free->arch.rmap[i]);
  5520. free->arch.rmap[i] = NULL;
  5521. }
  5522. if (i == 0)
  5523. continue;
  5524. if (!dont || free->arch.lpage_info[i - 1] !=
  5525. dont->arch.lpage_info[i - 1]) {
  5526. kvm_kvfree(free->arch.lpage_info[i - 1]);
  5527. free->arch.lpage_info[i - 1] = NULL;
  5528. }
  5529. }
  5530. }
  5531. int kvm_arch_create_memslot(struct kvm_memory_slot *slot, unsigned long npages)
  5532. {
  5533. int i;
  5534. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5535. unsigned long ugfn;
  5536. int lpages;
  5537. int level = i + 1;
  5538. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  5539. slot->base_gfn, level) + 1;
  5540. slot->arch.rmap[i] =
  5541. kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
  5542. if (!slot->arch.rmap[i])
  5543. goto out_free;
  5544. if (i == 0)
  5545. continue;
  5546. slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
  5547. sizeof(*slot->arch.lpage_info[i - 1]));
  5548. if (!slot->arch.lpage_info[i - 1])
  5549. goto out_free;
  5550. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  5551. slot->arch.lpage_info[i - 1][0].write_count = 1;
  5552. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  5553. slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
  5554. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  5555. /*
  5556. * If the gfn and userspace address are not aligned wrt each
  5557. * other, or if explicitly asked to, disable large page
  5558. * support for this slot
  5559. */
  5560. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  5561. !kvm_largepages_enabled()) {
  5562. unsigned long j;
  5563. for (j = 0; j < lpages; ++j)
  5564. slot->arch.lpage_info[i - 1][j].write_count = 1;
  5565. }
  5566. }
  5567. return 0;
  5568. out_free:
  5569. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5570. kvm_kvfree(slot->arch.rmap[i]);
  5571. slot->arch.rmap[i] = NULL;
  5572. if (i == 0)
  5573. continue;
  5574. kvm_kvfree(slot->arch.lpage_info[i - 1]);
  5575. slot->arch.lpage_info[i - 1] = NULL;
  5576. }
  5577. return -ENOMEM;
  5578. }
  5579. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  5580. struct kvm_memory_slot *memslot,
  5581. struct kvm_memory_slot old,
  5582. struct kvm_userspace_memory_region *mem,
  5583. int user_alloc)
  5584. {
  5585. int npages = memslot->npages;
  5586. int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
  5587. /* Prevent internal slot pages from being moved by fork()/COW. */
  5588. if (memslot->id >= KVM_MEMORY_SLOTS)
  5589. map_flags = MAP_SHARED | MAP_ANONYMOUS;
  5590. /*To keep backward compatibility with older userspace,
  5591. *x86 needs to handle !user_alloc case.
  5592. */
  5593. if (!user_alloc) {
  5594. if (npages && !old.npages) {
  5595. unsigned long userspace_addr;
  5596. userspace_addr = vm_mmap(NULL, 0,
  5597. npages * PAGE_SIZE,
  5598. PROT_READ | PROT_WRITE,
  5599. map_flags,
  5600. 0);
  5601. if (IS_ERR((void *)userspace_addr))
  5602. return PTR_ERR((void *)userspace_addr);
  5603. memslot->userspace_addr = userspace_addr;
  5604. }
  5605. }
  5606. return 0;
  5607. }
  5608. void kvm_arch_commit_memory_region(struct kvm *kvm,
  5609. struct kvm_userspace_memory_region *mem,
  5610. struct kvm_memory_slot old,
  5611. int user_alloc)
  5612. {
  5613. int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
  5614. if (!user_alloc && !old.user_alloc && old.npages && !npages) {
  5615. int ret;
  5616. ret = vm_munmap(old.userspace_addr,
  5617. old.npages * PAGE_SIZE);
  5618. if (ret < 0)
  5619. printk(KERN_WARNING
  5620. "kvm_vm_ioctl_set_memory_region: "
  5621. "failed to munmap memory\n");
  5622. }
  5623. if (!kvm->arch.n_requested_mmu_pages)
  5624. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  5625. spin_lock(&kvm->mmu_lock);
  5626. if (nr_mmu_pages)
  5627. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  5628. kvm_mmu_slot_remove_write_access(kvm, mem->slot);
  5629. spin_unlock(&kvm->mmu_lock);
  5630. /*
  5631. * If memory slot is created, or moved, we need to clear all
  5632. * mmio sptes.
  5633. */
  5634. if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) {
  5635. kvm_mmu_zap_all(kvm);
  5636. kvm_reload_remote_mmus(kvm);
  5637. }
  5638. }
  5639. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  5640. {
  5641. kvm_mmu_zap_all(kvm);
  5642. kvm_reload_remote_mmus(kvm);
  5643. }
  5644. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  5645. struct kvm_memory_slot *slot)
  5646. {
  5647. kvm_arch_flush_shadow_all(kvm);
  5648. }
  5649. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  5650. {
  5651. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  5652. !vcpu->arch.apf.halted)
  5653. || !list_empty_careful(&vcpu->async_pf.done)
  5654. || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
  5655. || atomic_read(&vcpu->arch.nmi_queued) ||
  5656. (kvm_arch_interrupt_allowed(vcpu) &&
  5657. kvm_cpu_has_interrupt(vcpu));
  5658. }
  5659. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  5660. {
  5661. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  5662. }
  5663. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  5664. {
  5665. return kvm_x86_ops->interrupt_allowed(vcpu);
  5666. }
  5667. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  5668. {
  5669. unsigned long current_rip = kvm_rip_read(vcpu) +
  5670. get_segment_base(vcpu, VCPU_SREG_CS);
  5671. return current_rip == linear_rip;
  5672. }
  5673. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  5674. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  5675. {
  5676. unsigned long rflags;
  5677. rflags = kvm_x86_ops->get_rflags(vcpu);
  5678. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  5679. rflags &= ~X86_EFLAGS_TF;
  5680. return rflags;
  5681. }
  5682. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  5683. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  5684. {
  5685. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  5686. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  5687. rflags |= X86_EFLAGS_TF;
  5688. kvm_x86_ops->set_rflags(vcpu, rflags);
  5689. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5690. }
  5691. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  5692. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  5693. {
  5694. int r;
  5695. if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
  5696. is_error_page(work->page))
  5697. return;
  5698. r = kvm_mmu_reload(vcpu);
  5699. if (unlikely(r))
  5700. return;
  5701. if (!vcpu->arch.mmu.direct_map &&
  5702. work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  5703. return;
  5704. vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  5705. }
  5706. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  5707. {
  5708. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  5709. }
  5710. static inline u32 kvm_async_pf_next_probe(u32 key)
  5711. {
  5712. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  5713. }
  5714. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  5715. {
  5716. u32 key = kvm_async_pf_hash_fn(gfn);
  5717. while (vcpu->arch.apf.gfns[key] != ~0)
  5718. key = kvm_async_pf_next_probe(key);
  5719. vcpu->arch.apf.gfns[key] = gfn;
  5720. }
  5721. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  5722. {
  5723. int i;
  5724. u32 key = kvm_async_pf_hash_fn(gfn);
  5725. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  5726. (vcpu->arch.apf.gfns[key] != gfn &&
  5727. vcpu->arch.apf.gfns[key] != ~0); i++)
  5728. key = kvm_async_pf_next_probe(key);
  5729. return key;
  5730. }
  5731. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  5732. {
  5733. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  5734. }
  5735. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  5736. {
  5737. u32 i, j, k;
  5738. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  5739. while (true) {
  5740. vcpu->arch.apf.gfns[i] = ~0;
  5741. do {
  5742. j = kvm_async_pf_next_probe(j);
  5743. if (vcpu->arch.apf.gfns[j] == ~0)
  5744. return;
  5745. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  5746. /*
  5747. * k lies cyclically in ]i,j]
  5748. * | i.k.j |
  5749. * |....j i.k.| or |.k..j i...|
  5750. */
  5751. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  5752. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  5753. i = j;
  5754. }
  5755. }
  5756. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  5757. {
  5758. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  5759. sizeof(val));
  5760. }
  5761. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  5762. struct kvm_async_pf *work)
  5763. {
  5764. struct x86_exception fault;
  5765. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  5766. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  5767. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  5768. (vcpu->arch.apf.send_user_only &&
  5769. kvm_x86_ops->get_cpl(vcpu) == 0))
  5770. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  5771. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  5772. fault.vector = PF_VECTOR;
  5773. fault.error_code_valid = true;
  5774. fault.error_code = 0;
  5775. fault.nested_page_fault = false;
  5776. fault.address = work->arch.token;
  5777. kvm_inject_page_fault(vcpu, &fault);
  5778. }
  5779. }
  5780. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  5781. struct kvm_async_pf *work)
  5782. {
  5783. struct x86_exception fault;
  5784. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  5785. if (is_error_page(work->page))
  5786. work->arch.token = ~0; /* broadcast wakeup */
  5787. else
  5788. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  5789. if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
  5790. !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  5791. fault.vector = PF_VECTOR;
  5792. fault.error_code_valid = true;
  5793. fault.error_code = 0;
  5794. fault.nested_page_fault = false;
  5795. fault.address = work->arch.token;
  5796. kvm_inject_page_fault(vcpu, &fault);
  5797. }
  5798. vcpu->arch.apf.halted = false;
  5799. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  5800. }
  5801. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  5802. {
  5803. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  5804. return true;
  5805. else
  5806. return !kvm_event_needs_reinjection(vcpu) &&
  5807. kvm_x86_ops->interrupt_allowed(vcpu);
  5808. }
  5809. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  5810. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  5811. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  5812. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  5813. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  5814. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  5815. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  5816. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  5817. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  5818. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  5819. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  5820. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);