x86.c 180 KB

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