x86.c 218 KB

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