x86.c 239 KB

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