x86.c 182 KB

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