x86.c 186 KB

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