x86.c 215 KB

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