x86.c 245 KB

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