x86.c 180 KB

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