x86.c 167 KB

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