x86.c 187 KB

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