x86.c 186 KB

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