x86.c 190 KB

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