x86.c 197 KB

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