x86.c 186 KB

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