x86.c 210 KB

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