x86.c 215 KB

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